使用带有MapSpaFallbackRoute的命名路由

时间:2017-10-16 15:55:21

标签: asp.net asp.net-core asp.net-core-mvc asp.net-mvc-routing single-page-application

我在ASP.NET Core SPA中使用命名路由,如下所示:

[HttpGet("", Name = HomeControllerRouteName.GetIndex)]
public IActionResult Index() => this.View();

在我的Startup.cs中,我使用MapSpaFallbackRoute方法回退到单页应用程序以显示404错误页面。它目前使用控制器和操作名称来确定后备路由,如下所示:

application.UseMvc(
    routes =>
    {
        routes.MapSpaFallbackRoute(
            name: "spa-fallback",
            defaults: new { controller = "Home", action = "Index" });
    });

我想在我的Startup.cs中使用命名路由来保持一致性。如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

示例取自:https://github.com/aspnet/JavaScriptServices/issues/973

有条件地映射SPA备用路由

// API Routes
       app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        // This route will never be mapped when route starts with api
        app.MapWhen(x => !x.Request.Path.Value.StartsWith("/api"), builder =>
        {
            builder.UseMvc(routes =>
            {
                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        });