MVC 6 Routing, SPA fallback + 404 Error Page

前端 未结 3 852

With RC1 of ASP.NET Core 1.0\'s MVC 6 you can map routes from within your Startup.Configure function when invoking app.UseMvc. I h

3条回答
  •  走了就别回头了
    2021-01-02 11:32

    It took me some time to figure out how to do this without serving my index using MVC and to still receive 404s for missing files. Here's my http pipeline:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseDefaultFiles();
            app.UseStaticFiles();
    
            app.UseMvc(                
                routes => {
                    routes.MapRoute(
                        name: "api",
                        template: "api/{controller}/{action}/{id?}");
    
                    // ## commented out since I don't want to use MVC to serve my index.    
                    // routes.MapRoute(
                    //     name:"spa-fallback", 
                    //     template: "{*anything}", 
                    //     defaults: new { controller = "Home", action = "Index" });
            });
    
            // ## this serves my index.html from the wwwroot folder when 
            // ## a route not containing a file extension is not handled by MVC.  
            // ## If the route contains a ".", a 404 will be returned instead.
            app.MapWhen(context => context.Response.StatusCode == 404 &&
                                   !Path.HasExtension(context.Request.Path.Value),
                        branch => {
                               branch.Use((context, next) => {
                                   context.Request.Path = new PathString("/index.html");
                                   Console.WriteLine("Path changed to:" + context.Request.Path.Value);
                                   return next();});
    
                        branch.UseStaticFiles();
            });            
        }
    

提交回复
热议问题