[C#] ASP.NET Core 6.0 - 不透過 Web.Config 處理錯誤導頁 ex. 404 , 500 ...等錯誤

2023-01-30

今天討論一下如何將客戶導向錯誤訊息,以前再寫 ASP.net Webform 時代,可以設定 Web.Config 來解處理這問題

但是現在到了 .Net Core 時代,機器不一定是跑在 IIS 上面,可能是 Linux ,所以這得處理一下


因為這邊基於 .Net 6 ,所以已經沒有 Startup.cs 所以對 Program.cs 中改寫


public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // Add This else { app.UseStatusCodePagesWithReExecute("/CError/{0}"); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapRazorPages(); app.Run(); }


在程式碼中,會被我導入 /CError 透過 CError透過 CError 來處理要對客戶的相關導入畫面

CError.cshtml.cs

using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Core6Tutorial.Pages { public class CErrorModel : PageModel { public string ErrorMessage { get; set; } public IActionResult OnGet(int errorInfo) { switch (errorInfo) { case 404: ErrorMessage = "該頁面不存在,抱歉"; break; case 500: ErrorMessage = "500 錯誤動作..."; break; } return Page(); } } }


CError.cshtml

@page "{errorInfo?}" @model Core6Tutorial.Pages.CErrorModel @{ } @Html.Raw(Model.ErrorMessage)


這裡面我也附上關於模擬 500 的錯誤觸發程式碼,測了一下沒啥問題


模擬發出 500錯誤

using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Core6Tutorial.Pages { public class throw500errrorModel : PageModel { public IActionResult OnGet() { return new StatusCodeResult(StatusCodes.Status500InternalServerError); } } }




如果有需要更詳細了解的可以參考下面文章

https://dotblogs.com.tw/supershowwei/2021/04/14/185800

https://stackoverflow.com/questions/37793418/how-to-return-http-500-from-asp-net-core-rc2-web-api

https://stackoverflow.com/questions/73871374/custom-404-page-on-azure-app-service-linux-asp-net-core-webapp

https://stackoverflow.com/questions/74352278/how-to-redirect-notfound-to-my-custom-404-page-in-asp-net-core-6-mvc





當麻許的碎念筆記 2014 | Donma Hsu Design.