欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在ASP.NET Core中显示自定义的错误页面

程序员文章站 2022-06-09 09:20:02
前言 相信每位程序员们应该都知道在 asp.net core 中,默认情况下当发生500或404错误时,只返回http状态码,不返回任何内容,页面一片空白。 如果在 s...

前言

相信每位程序员们应该都知道在 asp.net core 中,默认情况下当发生500或404错误时,只返回http状态码,不返回任何内容,页面一片空白。

如果在 startup.cs 的 configure() 中加上 app.usestatuscodepages(); ,500错误时依然是一片空白(不知为何对500错误不起作用),404错误时有所改观,页面会显示下面的文字:

status code: 404; not found 

如果我们想实现不管500还是404错误都显示自己定制的友好错误页面,那该怎么办呢?

对于500错误,我们可以用 app.useexceptionhandler() 进行截获;

对于404错误,我们可以用 app.usestatuscodepages() 的增强版 app.usestatuscodepageswithreexecute() 进行截获;

然后转交给相应的url进行处理。

app.useexceptionhandler("/errors/500");
app.usestatuscodepageswithreexecute("/errors/{0}");

url 路由到 mvc controller 中显示友好错误页面。

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");
 }  
}

【更新】

后来发现一个问题,当出现底层异常时,自定义错误页面不能显示,还是一片空白,比如下面的异常:

system.dllnotfoundexception: unable to load dll 'system.security.cryptography.native.apple': the specified module could not be found.
 (exception from hresult: 0x8007007e)

这时想到用 mvc 显示自定义错误页面的局限,如果发生的异常导致 mvc 本身不能正常工作,自定义错误页面就无法显示。

于是针对这个问题进行了改进,针对500错误直接用静态文件的方式进行响应,startup.cs 的 configure() 中的代码如下:

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}");

为了重用自定义错误页面,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"));
 }  
}

总结

以上就是关于asp.net core中显示自定义错误页面的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。