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

后端 未结 3 1805
夕颜
夕颜 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 05:34

    Works with various status codes without specifying each one individually in the controller.

    Startup.cs:

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        app.UseStatusCodePagesWithRedirects("/StatusCodes?statusCode={0}");
        app.UseMvcWithDefaultRoute();
    

    Controller:

      public class StatusCodesController : Controller
      {
        public IActionResult Index(string statusCode)
        {
          if(statusCode == null) statusCode = "";
          if(statusCode == "404") return View("Error404");
          return View("Index",statusCode);
        }
    
        public IActionResult Test404() { return StatusCode(404); }
        public IActionResult Test500() { return StatusCode(500); }
    

    View:

    @model string
    @{ ViewData["Title"] = Model + " Oops!"; }
    
    
    
    

    Oops!

    @Model Error

    Sorry, an error has occurred!

提交回复
热议问题