Dav*_*ine 8 c# asp.net-mvc-routing asp.net-core-mvc angular2-routing
使用ASP.NET Core 1.0的MVC 6的RC1,您可以在调用时映射函数内的路径.我已经映射了一个"spa-fallback"路由,它将确保和视图是默认值,如下所示:Startup.Configureapp.UseMvcHomeControllerIndex
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
// ... omitted for brevity
app.UseExceptionHandler("/Home/Error");
app.UseStatusCodePagesWithRedirects("/Home/Error/{0}");
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute("spa-fallback", "{*anything}", new { controller = "Home", action = "Index" });
routes.MapWebApiRoute("defaultApi", "api/{controller}/{id?}");
});
}
Run Code Online (Sandbox Code Playgroud)
我希望回退,以便我的Angular2应用程序的路由不会导致HTTP状态代码404,Not Found.但是,当用户无意中尝试导航到不存在的页面视图时,我还需要正确处理.你可能会注意到我也打过电话app.UseStatusCodePagesWithRedirects("/Home/Error/{0}");.
使用状态代码和"spa-fallback"路由重定向到我的错误页面的调用似乎是互斥的 - 这意味着我似乎只能拥有一个或另一个(但遗憾的是不是两者).有谁知道如何才能让两全其美?
Jam*_*mer 14
我花了一些时间来弄清楚如何在不使用MVC提供索引的情况下执行此操作,并仍然收到丢失文件的404.这是我的http管道:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc(
routes => {
routes.MapRoute(
name: "api",
template: "api/{controller}/{action}/{id?}");
// ## commented out since I don't want to use MVC to serve my index.
// routes.MapRoute(
// name:"spa-fallback",
// template: "{*anything}",
// defaults: new { controller = "Home", action = "Index" });
});
// ## this serves my index.html from the wwwroot folder when
// ## a route not containing a file extension is not handled by MVC.
// ## If the route contains a ".", a 404 will be returned instead.
app.MapWhen(context => context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value),
branch => {
branch.Use((context, next) => {
context.Request.Path = new PathString("/index.html");
Console.WriteLine("Path changed to:" + context.Request.Path.Value);
return next();});
branch.UseStaticFiles();
});
}
Run Code Online (Sandbox Code Playgroud)
我想出了两种可能的解决方法/解决方案。
ASP.NET 核心 1.0,RC1
特别是对于Angular2,我们可以简单地将LocationStrategy. 例如在我的wwwroot/app/boot.ts我有以下内容:
import {provide} from "angular2/core";
import {bootstrap} from "angular2/platform/browser";
import {LocationStrategy, HashLocationStrategy, ROUTER_PROVIDERS} from "angular2/router";
import {HTTP_PROVIDERS} from "angular2/http";
import {AppComponent} from "./app.component"
bootstrap(AppComponent,
[
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy })
]);
Run Code Online (Sandbox Code Playgroud)
请注意,我正在利用该provide函数LocationStrategy用HashLocationStrategy. 这会#在 URL 中添加并防止 MVC 错误地抛出404's,而且当用户手动输入不存在的URL时,也会正确处理404's响应。
ASP.NET 核心 1.0,RC2
只需使用Microsoft.AspNet.NodeServices. 在这个库中,有AngularServices和ReactServices允许通过MapSpaFallbackRoute函数专门映射 SPA 路由。我声明我们需要等待RC2,并理解当前的实现并没有完全按预期运行。