亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

在ASP.NET Core中顯示自定義的錯誤頁面

Original 2017-01-12 09:51:04 342
abstract:前言相信每位程序員們應(yīng)該都知道在 ASP.NET Core 中,默認情況下當(dāng)發(fā)生500或404錯誤時,只返回http狀態(tài)碼,不返回任何內(nèi)容,頁面一片空白。如果在 Startup.cs 的 Configure() 中加上 app.UseStatusCodePages(); ,500錯誤時依然是一片空白(不知為何對500錯誤不起作用),404錯誤時有所改觀,頁面會顯示下面的文字:S

前言

相信每位程序員們應(yīng)該都知道在 ASP.NET Core 中,默認情況下當(dāng)發(fā)生500或404錯誤時,只返回http狀態(tài)碼,不返回任何內(nèi)容,頁面一片空白。

如果在 Startup.cs 的 Configure() 中加上 app.UseStatusCodePages(); ,500錯誤時依然是一片空白(不知為何對500錯誤不起作用),404錯誤時有所改觀,頁面會顯示下面的文字:

Status Code: 404; Not Found

   

如果我們想實現(xiàn)不管500還是404錯誤都顯示自己定制的友好錯誤頁面,那該怎么辦呢?

對于500錯誤,我們可以用 app.UseExceptionHandler() 進行截獲;

對于404錯誤,我們可以用 app.UseStatusCodePages() 的增強版 app.UseStatusCodePagesWithReExecute()進行截獲;

然后轉(zhuǎn)交給相應(yīng)的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");
 } 
}

【更新】

后來發(fā)現(xiàn)一個問題,當(dāng)出現(xiàn)底層異常時,自定義錯誤頁面不能顯示,還是一片空白,比如下面的異常:

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

這時想到用 MVC 顯示自定義錯誤頁面的局限,如果發(fā)生的異常導(dǎo)致 MVC 本身不能正常工作,自定義錯誤頁面就無法顯示。

于是針對這個問題進行了改進,針對500錯誤直接用靜態(tài)文件的方式進行響應(yīng),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"));
 } 
}

更多關(guān)于在ASP.NET Core中顯示自定義的錯誤頁面請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!   


Release Notes

Popular Entries