ASP.NET MVC 6 handling errors based on HTTP status code

后端 未结 3 1797
夕颜
夕颜 2021-02-20 05:12

I want to display different error messages for each status code e.g:

  • 400 Bad Request
  • 403 Forbidden
  • 500 Internal Server Error
  • 404 Not Fou
3条回答
  •  眼角桃花
    2021-02-20 06:00

    You could use the StatusCodePagesMiddleware for this. Following is an example:

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        app.UseStatusCodePagesWithReExecute("/StatusCodes/StatusCode{0}");
    
        app.UseMvcWithDefaultRoute();
    

    Controller which handles the status code requests:

    public class StatusCodesController : Controller
    {
        public IActionResult StatusCode404()
        {
            return View(viewName: "NotFound"); // you have a view called NotFound.cshtml
        }
    
        ... more actions here to handle other status codes
    }
    

    Some Notes:

    • Check other extension methods like UseStatusCodePagesWithRedirects and UseStatusCodePages for other capabilities.
    • I tried having StatusCode as a query string in my example, but looks like this middleware doesn't handle query strings, but you can take a look at this code and fix this issue.

提交回复
热议问题