Display custom error pages in ASP. NET Core

  • 2021-08-31 07:41:56
  • OfStack

Preface

I believe every programmer should know that in ASP. NET Core, by default, when a 500 or 404 error occurs, only http status code is returned, nothing is returned, and the page is blank.

If you add Configure () in Startup. cs app.UseStatusCodePages(); For 500 errors, it is still 1 blank (somehow it doesn't work for 500 errors), and for 404 errors, it changes, and the page will display the following text:


Status Code: 404; Not Found 

What if we wanted to make our own custom error-friendly page available regardless of 500 or 404 errors?

For 500 errors, we can use app.UseExceptionHandler() Intercept;

For 404 errors, we can use app.UseStatusCodePages() Enhanced version of app.UseStatusCodePagesWithReExecute() Intercept;

Then it is transferred to the corresponding URL for processing.


app.UseExceptionHandler("/errors/500");
app.UseStatusCodePagesWithReExecute("/errors/{0}");

URL routing to MVC Controller displays a friendly error page.


public class ErrorsController : Controller
{
 [Route("errors/{statusCode}")]
 public IActionResult CustomError(int statusCode)
 {
  if(statusCode == 404)
  {
   return View("~/Views/Errors/404.cshtml");
  }
  return View("~/Views/Errors/500.cshtml");
 }  
}

"Update"

Later, I found a problem. When the underlying exception occurs, the custom error page cannot be displayed, or it is still blank, such as the following exception:


System.DllNotFoundException: Unable to load DLL 'System.Security.Cryptography.Native.Apple': The specified module could not be found.
 (Exception from HRESULT: 0x8007007E)

At this time, I think of the limitations of displaying custom error pages with MVC. If an exception occurs, MVC itself will not work properly, and the custom error pages will not be displayed.

Therefore, this problem has been improved, and the response to 500 errors is directly made by static files, Startup. cs Configure() The code in:


app.UseExceptionHandler(errorApp =>
{
 errorApp.Run(async context =>
 {
  context.Response.StatusCode = 500;
  if (context.Request.Headers["X-Requested-With"] != "XMLHttpRequest")
  {
   context.Response.ContentType = "text/html";
   await context.Response.SendFileAsync($@"{env.WebRootPath}/errors/500.html");
  }
 });
});
app.UseStatusCodePagesWithReExecute("/errors/{0}");

To reuse custom error pages, changes have been made in MVC Controller:


public class ErrorsController : Controller
{
 private IHostingEnvironment _env;

 public ErrorsController(IHostingEnvironment env)
 {
  _env = env;
 }

 [Route("errors/{statusCode}")]
 public IActionResult CustomError(int statusCode)
 {
  var filePath = $"{_env.WebRootPath}/errors/{(statusCode == 404?404:500)}.html";
  return new PhysicalFileResult(filePath, new MediaTypeHeaderValue("text/html"));
 }  
}

Summarize

The above is all about the custom error page displayed in ASP. NET Core. I hope the content of this article can bring 1 certain help to your study or work. If you have any questions, you can leave a message for communication.


Related articles: