MapSpaFallbackRoute on Startup ASP .NET Core

2019-09-02 11:06发布

I have an Areas on Net Core App named Admin, on MapSpaFallbackRoute setting on startup, I want to set like this,

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

is this the correct way to define MapSpaFallbackRoute? I doubt MapSpaFallbackRoute have attributes area, I have been try this, and my apps return 404(not found). so, what the correct way to define MapSpaFallbackRoute, I want using HomeController on Admin area, with Index action

It is my complete code, I want to request with path admin, controller on admin areas should be handle that.

        app.MapWhen(context => context.Request.Path.Value.StartsWith("/admin"), builder =>
        {
            builder.UseMvc(routes =>
            {
                routes.MapRoute(
                name: "default",
                template: "{area=Admin}/{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                name: "spa-fallback-admin",
                defaults: new { area="Admin", controller = "Home", action = "Index" });
            });
        });

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

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
            routes.MapRoute(
                name: "areas",
                template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
        });

thanks for your help

1条回答
Emotional °昔
2楼-- · 2019-09-02 11:54

What MapSpaFallbackRoute does is allows defining default values for route parameters to handle 404 cases.

Now to your question: yes, MVC routing (both attribute/convention) supports {area} as route parameter and so you can write above code to define a default value.

You didn't show your routing setup, so I assume that your main problem is that you haven't specified {area} parameter in your route template.

For example, if consider convention routing, the following should work:

app.UseMvc(routes => {
           routes.MapRoute("default", "{area}/{controller}/{action}/{id?}");
           routes.MapSpaFallbackRoute(
             name: "spa-fallback-admin",
             defaults: new { area="Admin", controller = "Home", action = "Index" });
});

For updated question: Try to use .UseWhen instead of .MapWhen:

app.UseWhen(context => context.Request.Path.Value.StartsWith("/admin"), builder =>
{
查看更多
登录 后发表回答