5
votes

I am using named routes in my ASP.NET Core SPA like so:

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

In my Startup.cs I use the MapSpaFallbackRoute method to fallback to the single page application to show 404 error pages. It currently uses the controller and action name to determine the fallback route like so:

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

I would like to do use named routes in my Startup.cs for consistency. How can this be achieved?

1
You are showing an example of a named route (the MapSpaFallbackRoute), so it is not clear what your question is. - NightOwl888
You are mistaken. That is not a named route. It uses a controller and action name. - Muhammad Rehan Saeed
MapSpaFallbackRoute has a value for the (optional) name argument. That means it is a named route. Your first example is a named attribute route. Are you saying you want to setup a fallback attribute route? - NightOwl888

1 Answers

0
votes

Example taken from: https://github.com/aspnet/JavaScriptServices/issues/973

Map SPA fallback route conditionally

// 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" });
            });
        });