常用處理方式
自己定制網(wǎng)站的404、500頁(yè)面的方式有很多,比如修改nginx配置文件,指定請(qǐng)求返回碼對(duì)應(yīng)的頁(yè)面,
.netframework項(xiàng)目中修改webconfig文件,指定customerror節(jié)點(diǎn)的文件路徑都可以。
在那么在.net core中如何處理呢。
500錯(cuò)誤頁(yè)
- 500的錯(cuò)誤都是靠攔截處理,在.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 創(chuàng)建的時(shí)候也自帶了錯(cuò)誤頁(yè)的管道處理
在 startup.cs中
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//開發(fā)環(huán)境直接展示錯(cuò)誤堆棧的頁(yè)面
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
//正式環(huán)境自定義錯(cuò)誤頁(yè)
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頁(yè)面
通過(guò)上述方法是攔截不到404頁(yè)面的,應(yīng)該借助管道的中間件去處理,在 startup.cs文件的 configure方法中添加
app.UseStatusCodePagesWithReExecute("/error/{0}");
添加 error控制器
public class ErrorController : Controller
{
/// <summary>
/// {0}中是錯(cuò)誤碼
/// </summary>
/// <returns></returns>
[Route("/error/{0}")]
public IActionResult Page()
{
//跳轉(zhuǎn)到404錯(cuò)誤頁(yè)
if (Response.StatusCode == 404)
{
return View("/views/error/notfound.cshtml");
}
return View();
}
}
需要注意的是錯(cuò)誤頁(yè)攔截不要寫在這里在上面的 app.UseExceptionHandler("/Home/Error"); 控制器中處理就行了