常用處理方式
自己定制網站的404、500頁面的方式有很多,比如修改nginx配置文件,指定請求返回碼對應的頁面,
.netframework項目中修改webconfig文件,指定customerror節點的文件路徑都可以。
在那么在.net core中如何處理呢。
500錯誤頁
- 500的錯誤都是靠攔截處理,在.netcore mvc攔截器中處理也可以。
public class ErrorPageFilter : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext context)
{
if (context.HttpContext.Response.StatusCode == 500)
{
context.HttpContext.Response.Redirect("error/500");
}
base.OnResultExecuted(context);
}
}
[ErrorPageFilter]
public abstract class PageController
{}
- .net core mvc 創建的時候也自帶了錯誤頁的管道處理
在 startup.cs中
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//開發環境直接展示錯誤堆棧的頁面
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
//正式環境自定義錯誤頁
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
}
在 home控制器中 有這樣的方法
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
自己把 error視圖文件替換掉自己想要的樣式就可以了。
404頁面
通過上述方法是攔截不到404頁面的,應該借助管道的中間件去處理,在 startup.cs文件的 configure方法中添加
app.UseStatusCodePagesWithReExecute("/error/{0}");
添加 error控制器
public class ErrorController : Controller
{
/// <summary>
/// {0}中是錯誤碼
/// </summary>
/// <returns></returns>
[Route("/error/{0}")]
public IActionResult Page()
{
//跳轉到404錯誤頁
if (Response.StatusCode == 404)
{
return View("/views/error/notfound.cshtml");
}
return View();
}
}
需要注意的是錯誤頁攔截不要寫在這里在上面的 app.UseExceptionHandler("/Home/Error"); 控制器中處理就行了