使用ASP.Net Core MVC和ASP.Net Web Api在Angular2 App中进行HTML5路由

Sup*_*der 4 asp.net-core-mvc asp.net-core-webapi angular

我正在使用ASP.Net Core MVC和ASP.Net Web Api开发Angular2 App.

这是我的基本架构.

ASP.Net核心MVC项目(MyProject.Web)

  • Nuget,npmbower用于依赖.Bower用于将npm依赖项从中复制node_moduleswwwroot/libs/
  • Home/Indexcontroller的动作提供加载Angular2和其他依赖项的第一页.
  • 模板从ActionMethods加载,即 Home/About
  • SystemJS加载模块.
  • Angular2的http服务调用ASP.Net Web Api项目(一个单独的项目而不是mvc)

ASP.Net Web Api项目(MyProject.Api) - 每个控制器被指定用于实体的CRUD操作,并响应Angular2的http

问题:我无法使用HTML5路由并被迫散列路由,因为html5路由调用服务器而我的MVC项目没有相应的控制器.所以服务器不会返回任何内容.

Win*_*Win 6

如果您打算在IIS上使用,则可以使用URL重写模块.它基本上告诉Web服务器将所有路由URL重写为index.html..

<?xml version="1.0" encoding="utf-8"?>
<system.webServer>
   <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule"
resourceType="Unspecified"/>
   </handlers>
   <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%"
stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout"
forwardWindowsAuthToken="false" />
      <rewrite>
         <rules>
            <rule name="Angular 2 pushState routing" 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_FILENAME}" pattern=".*\.[\d\w]+$" negate="true" />
                  <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
               </conditions>
               <action type="Rewrite" url="/index.html" />
            </rule>
         </rules>
      </rewrite>
   </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)