ASP.net core MVC catch all route serve static file

前端 未结 7 2321
悲&欢浪女
悲&欢浪女 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:09

    ASP.NET Core catch all routes for Web API and MVC are configured differently

    With Web API (if you're using prefix "api" for all server-side controllers eg. Route("api/[controller"]):

    app.Use(async (context, next) => 
    { 
        await next(); 
        var path = context.Request.Path.Value;
    
        if (!path.StartsWith("/api") && !Path.HasExtension(path)) 
        { 
            context.Request.Path = "/index.html"; 
            await next(); 
        } 
    });            
    
    app.UseStaticFiles();
    app.UseDefaultFiles();
    
    app.UseMvc();
    

    With MVC (dotnet add package Microsoft.AspNetCore.SpaServices -Version x.y.z):

    app.UseStaticFiles();
    app.UseDefaultFiles();
    
    app.UseMvc(routes => 
    { 
        routes.MapRoute( 
            name: "default", 
            template: "{controller=Home}/{action=Index}"); 
    
        routes.MapSpaFallbackRoute("spa", new { controller = "Home", action = "Index" }); 
    });  
    

提交回复
热议问题