ASP.net core MVC catch all route serve static file

前端 未结 7 2234
悲&欢浪女
悲&欢浪女 2020-12-13 09:20

Is there a way to make a catch all route serve a static file?

Looking at this http://blog.nbellocam.me/2016/03/21/routing-angular-2-asp-net-core/

I basically

相关标签:
7条回答
  • 2020-12-13 10:17

    What I'm using that works well is Microsoft.AspNetCore.Builder.SpaRouteExtensions.MapSpaFallbackRoute:

    app.UseMvc(routes =>
    {
        // Default route for SPA components, excluding paths which appear to be static files (have an extension)
        routes.MapSpaFallbackRoute(
            "spaFallback",
            new { controller = "Home", action = "Index" });
    });
    

    HomeController.Index has the equivalent of your index.html. You can probably route to a static page also.

    A bit off topic, but if you also have an API in the same project under an api folder you can set a default 404 response for any API routes that don't match:

    routes.MapRoute(
        "apiDefault",
        "api/{*url}",
        new { controller = "Home", action = "ApiNotFound" });
    

    You would end up with the following behavior:

    • /controller => No extension, so serve SPA default page from HomeController.Index and let SPA handle routing
    • /file.txt => Extension detected, serve static file
    • /api/controller => proper API response (use attribute routing or set up another map for the API controllers)
    • /api/non-existent-route => 404 NotFound() returned from HomeController.ApiNotFound

    In many cases you'll want an API in a separate project, but this is a viable alternative.

    0 讨论(0)
提交回复
热议问题