Routing an Angular 2 app with Web API

只愿长相守 提交于 2019-12-03 16:36:53
Dmitriy Kovalenko

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>
Cobus Kruger

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!