02.25 asp.net core 自定義錯誤頁面

簡介

這篇文章教學如何在asp.net core項目下面,自定義錯誤頁面,處理404,403等錯誤頁面。


官方文檔


https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1


實戰操作


在項目Startup.cs 中 Configure中增加app.UseStatusCodePagesWithReExecute


<code>     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)        {                        app.UseStatusCodePagesWithReExecute("/Home/ErrorStatusCode", "?statusCode={0}");/<code>


這個api,作用是把Exception,轉交給特定的控制器執行,我們例子裡,是給/Home 控制器下面的ErrorStatusCode方法處理。 後面第二個參數,是傳遞錯誤碼


我們看看具體的方法裡面怎麼處理,方法有一個參數int statusCode接收傳過來的錯誤碼參數,然後賦值到ViewData裡面,以備後面模板視圖來渲染。


<code>        public IActionResult ErrorStatusCode(int statusCode = 0)        {            ViewData["Title"] = "出錯啦";            ViewData["StatusCode"] = statusCode;            return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});        }/<code>


然後創建一個模板位於:Views/Shared/ErrorStatusCode.cshtml


<code>@model ErrorViewModel

Error.

An error occurred while processing your request.

Status: @ViewData["StatusCode"]

@if (Model.ShowRequestId){

Request ID: <code>@Model.RequestId/<code>

}

Development Mode

Swapping to Development environment will display more detailed information about the error that occurred.

The Development environment shouldn't be enabled for deployed applications. It can result in displaying sensitive information from exceptions to end users. For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development and restarting the app.

/<code>


模板中顯示Status: @ViewData["statusCode"]


效果預覽


訪問一個不存在的頁面,就可以看到404錯誤頁面,效果如下


asp.net core 自定義錯誤頁面


分享到:


相關文章: