Routing an Angular 2 app with Web API

后端 未结 2 634
刺人心
刺人心 2021-02-10 14:20

I have an Angular 2 application created with Angular CLI. This has to call a .NET 4.6 Web API. The route setup of this is driving me nuts.

For Angular, the default folde

相关标签:
2条回答
  • 2021-02-10 14:59

    You need first disable web api routing for angular files, add this to web.config, inside <system.webServer> </system.webServer>:

    <rewrite>
      <rules>
        <rule name="AngularJS" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
    

    And then, add <base href="/"> to your index.html.

    UPD: Rewrite access to index.html

    You can add another rewrite rule to override access to your /dist/ folder:

    <rewrite>
        <rules>
            <rule name="DistAccess" stopProcessing="true">
                <match url="^(.*)/dist/(.*)" />
               <action type="Rewrite" url="{R:1}/{R:3}" />
            </rule>
        </rules>
    </rewrite>
    
    0 讨论(0)
  • 2021-02-10 14:59

    I just couldn't get Dmitriy's answer to work for me, but he did put me on the right track.

    I needed two rules: One to serve the Angular app from the root while maintaining the Web API /api/ routing, and another to serve the default document.

    Here they are:

    <rewrite>
      <rules>
          <rule name="Serve Angular app from root" stopProcessing="true">
            <match url="([\w\.]+)" />
            <conditions>
              <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
            </conditions>
            <action type="Rewrite" url="/dist/{R:1}" />
          </rule>
          <rule name="Default document" stopProcessing="true">
            <match url="^$" />
            <action type="Rewrite" url="/dist/index.html" />
          </rule>
        </rules>
    </rewrite>
    
    0 讨论(0)
提交回复
热议问题