.net core 自定義404 500頁(yè)面

常用處理方式

自己定制網(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"); 控制器中處理就行了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容