欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2016年12月09日 11:37:24   作者:dudu  
大家在用瀏覽器訪問服務器時,不同情況下會返回不同的信息。服務器發(fā)生錯誤就會返回錯誤信息,我們最熟悉的就是404錯誤頁面,但是這里我想和大家分享下在ASP.NET Core中如何顯示自定義的500或404錯誤頁面,有需要的朋友們可以參考借鑒,下面來一起看看吧。

前言

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

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

【更新】

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

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

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

于是針對這個問題進行了改進,針對500錯誤直接用靜態(tài)文件的方式進行響應,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中顯示自定義錯誤頁面的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。

相關文章

最新評論