Objective
Believe that every programmer should know that in ASP.net Core, when 500 or 404 errors occur by default, only the HTTP status code is returned, nothing is returned, and the page is blank.
If you add in the Startup.cs Configure () app.UseStatusCodePages();
, the 500 error is still blank (somehow not working for the 500 error), 404 errors are changed, the page will display the following text:
What if we want to achieve a custom friendly error page that no matter 500 or 404 error shows?
For 500 errors, we can use app.UseExceptionHandler()
to intercept;
For 404 errors, we can use app.UseStatusCodePages()
the enhanced version app.UseStatusCodePagesWithReExecute()
to intercept;
It is then forwarded to the appropriate URL for processing.
App. Useexceptionhandler ("/errors/500");
App. Usestatuscodepageswithreexecute ("/errors/{0}");
URLs are routed to the MVC Controller to display friendly error pages.
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, a problem was found that when the underlying exception occurred, the custom error page could not be displayed or blank, such as the following exception:
System.DllNotFoundException:Unable to load DLL ' System.Security.Cryptography.Native.Apple ': The specified module could Not to be found.
(Exception from hresult:0x8007007e)
When you think of the limitations of using MVC to display custom error pages, a custom error page cannot be displayed if an exception causes the MVC itself to not work correctly.
So to improve on this issue, for 500 errors directly in the form of static file response, Startup.cs Configure()
code as follows:
App. Useexceptionhandler (Errorapp =>
{
errorapp.run (Async context =>)
{context
. Response.statuscode = +;
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}");
In order to reuse the custom error page, the MVC Controller has been modified:
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 about ASP.net core display custom error page All content, hope this article content to everybody's study or work can bring certain help, if has the question everybody may message exchange.