asp.net-coreroutes.net-coreasp.net-mvc-areas

MapSpaFallbackRoute on Startup ASP .NET Core


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


Solution

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