Angular2应用程序中的HTML5路由与ASP.Net Core MVC和ASP.Net Web Api



我正在用ASP开发Angular2应用程序。Net Core MVC和ASP。Net Web Api。

这是我的基本架构。

ASP。Net Core MVC项目(MyProject.Web)

  • Nugetnpmbower用于依赖关系Bower用于将npm依赖项从node_modules复制到wwwroot/libs/
  • Home/Index控制器的操作提供加载Angular2和其他依赖项的第一个页面
  • 模板从ActionMethods加载,即Home/About
  • SystemJS加载模块
  • Angular2的http服务调用ASP。Net Web Api项目(一个独立于mvc的项目)

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

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

如果您计划在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=".logsstdout"
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=".*.[dw]+$" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

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

在像您这样的情况下,将#添加到路由路径中可能是最常见的解决方案,但是。。。

你有什么特别的理由将MVC与Angular结合使用吗?


在我看来,你不需要MVC-你可以创建空的ASP。NET核心项目,并添加到您的HTML/Angular应用程序中-干净、简单、舒适,MVC和Angular之间没有冲突;)

将您的文件(包括index.html)添加到wwwroot并更新您的Startup.cs文件:

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles(); <- Add this line before UseStaticFiles
app.UseStaticFiles();            
}
}


请查找更多信息:

  • ASP。NET核心处理静态文件
  • 将index.html作为ASP中的启动文件。NET核心

"我无法使用HTML5路由,被迫哈希路由,因为HTML5路由调用服务器,而我的MVC项目没有相应的控制器。所以服务器不会返回任何东西">

https://github.com/aspnet/JavaScriptServices

寻找路线助手,也就是水疗服务nuget和水疗后备路线。

如果找不到服务器端路由,并且路由没有文件扩展名,则应将index.html返回到客户端,其中当前路由被angular router解释为客户端路由。

最新更新