MapSpaFallbackRoute on Startup ASP .NET Core

旧时模样 提交于 2019-12-11 15:54:47

问题


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:


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 =>
{


来源:https://stackoverflow.com/questions/49669766/mapspafallbackroute-on-startup-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!