MVC 6 404 Not Found

前端 未结 6 1487
我在风中等你
我在风中等你 2020-12-06 12:04

Instead of getting a HTTP 404 response, I\'d like to have a generic 404 Not Found page (HTTP 200). I know you can set that up in MVC 5 with



        
6条回答
  •  清歌不尽
    2020-12-06 12:25

    You can handle 404 errors with the UseStatusCodePagesWithReExecute but you need to set the status code at the end of your configure pipeline first.

    public void Configure(IApplicationBuilder app)
        {
            app.UseIISPlatformHandler();
    
            if (string.Equals(_env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
            {
                app.UseDeveloperExceptionPage();
                app.UseRuntimeInfoPage();
            } else
            {
                app.UseExceptionHandler("/Error");
            }
            app.UseStatusCodePagesWithReExecute("/Error/Status/{0}");
    
            app.UseStaticFiles();
    
            app.UseMvc();
    
            app.Use((context, next) =>
            {
                context.Response.StatusCode = 404;
                return next();
            });
        }
    

    This will set the status code to 404 if nothing in the pipeline can handle it (which is what you want).

    Then you can easily capture and handle the response any way you want in your controller.

    [Route("error")]
    public class ErrorController : Controller
    {
    
    [Route("Status/{statusCode}")]
        public IActionResult StatusCode(int statusCode)
        {
    
                //logic to generate status code response
    
                return View("Status", model);
        }
    }
    

提交回复
热议问题