在ASP.NET Core使用Middleware模拟Custom Error Page功能
一、使用場(chǎng)景
在傳統(tǒng)的ASP.NET MVC中,我們可以使用HandleErrorAttribute特性來具體指定如何處理Action拋出的異常.只要某個(gè)Action設(shè)置了HandleErrorAttribute特性,那么默認(rèn)的,當(dāng)這個(gè)Action拋出了異常時(shí)MVC將會(huì)顯示Error視圖,該視圖位于~/Views/Shared目錄下。
自定義錯(cuò)誤頁面的目的,就是為了能讓程序在出現(xiàn)錯(cuò)誤/異常的時(shí)候,能夠有較好的顯示體驗(yàn)。有時(shí)候在Error視圖中也會(huì)發(fā)生錯(cuò)誤,這時(shí)ASP.NET/MVC將會(huì)顯示其默認(rèn)的錯(cuò)誤頁面(黃底紅字),為了避免這種情況的出現(xiàn),我們都是在Web.config文件的customErrors節(jié)中來自定義錯(cuò)誤頁面,來啟用自定義錯(cuò)誤處理:
?
<configuration><system.web><compilation debug="true" /><customErrors mode="On" defaultRedirect="DefaultError"><error statusCode="401" redirect="Http401Error"/><error statusCode="403" redirect="Http403Error"/><error statusCode="404" redirect="Http404Error"/><error statusCode="500" redirect="Http500Error"/></customErrors></system.web> </configuration>二、.NET Core實(shí)現(xiàn)
既然想用ASP.NET Core中的中間件模擬Custom Error Page功能,那首先我從配置下手。大家都知道.NET Core中配置文件系統(tǒng)發(fā)生了很大的變化,默認(rèn)都是采用Json格式的文件進(jìn)行存儲(chǔ)的,當(dāng)然配置文件也可以是其它類型的,這里我們就不深入探討了,我們就圍繞Json配置文件實(shí)現(xiàn)好了:
"ErrorPages": {"401": "/Error/Http401Page","403": "/Error/Http403Page","404": "/Error/Http404Page","500": "/Error/Http500Page" }我們?cè)赟tartup類中定義兩個(gè)變量,用來存儲(chǔ)配置文件讀取出來的信息如下:
public IConfigurationRoot Configuration { get; }internal static IDictionary<int, string> ErrorPages { get; } = new Dictionary<int, string>();配置文件中定義的ErrorPages節(jié)點(diǎn),用于存儲(chǔ)我們需要的Http狀態(tài)編碼并包含使用到的錯(cuò)誤頁面地址, 將他們用Startup類中的ErrorPages變量使用Key/Value的形式,讀取出來。
接下來我們要從JSON配置文件中讀取信息填充到ErrorPages:
var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true).AddEnvironmentVariables();Configuration = builder.Build();foreach (var c in Configuration.GetSection("ErrorPages").GetChildren()) {var key = Convert.ToInt32(c.Key);if (!ErrorPages.Keys.Contains(key)){ErrorPages.Add(key, c.Value);} }現(xiàn)在我們使用今天的主角,創(chuàng)建一個(gè)ASP.NET Core的Middleware,用于實(shí)現(xiàn)Custom Error Page功能:
public class CustomErrorPagesMiddleware {private readonly RequestDelegate _next;private readonly ILogger _logger;public CustomErrorPagesMiddleware(ILoggerFactory loggerFactory, RequestDelegate next){_next = next;_logger = loggerFactory.CreateLogger<CustomErrorPagesMiddleware>();}public async Task Invoke(HttpContext context){try{await _next(context);}catch (Exception ex){_logger.LogError(0, ex, "An unhandled exception has occurred while executing the request");if (context.Response.HasStarted){_logger.LogWarning("The response has already started, the error page middleware will not be executed.");throw;}try{context.Response.Clear();context.Response.StatusCode = 500;return;}catch (Exception ex2){_logger.LogError(0, ex2, "An exception was thrown attempting to display the error page.");}throw;}finally{var statusCode = context.Response.StatusCode;if (Startup.ErrorPages.Keys.Contains(statusCode)){context.Request.Path = Startup.ErrorPages[statusCode];await _next(context);}}}這樣就完成了,從響應(yīng)Response的StatusCode到配置的具體頁面的跳轉(zhuǎn)。
當(dāng)然我們最后,還要為這個(gè)中間件添加一個(gè)擴(kuò)展方法,ASP.NET Core中為 IApplictionBuilder創(chuàng)建了好多的擴(kuò)展方法,其實(shí)也好比它的名子一樣,它就應(yīng)該是一個(gè)建造者模式。
擴(kuò)展方法如下:
?
public static class BuilderExtensions {public static IApplicationBuilder UseCustomErrorPages(this IApplicationBuilder app){return app.UseMiddleware<CustomErrorPagesMiddleware>();} }?
最后在Startup類中的Configure方法中加入自定義錯(cuò)誤的擴(kuò)展:
app.UseCustomErrorPages();三、源代碼
如果你對(duì)文中的代碼感興趣,也可以到我的Github上去看下這個(gè)例子的源代碼:https://github.com/maxzhang1985/CustomErrorPages
?
------------------分割線--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
開源推廣:
YOYOFx,一個(gè)輕量級(jí)用于構(gòu)建基于 HTTP 的 Web 服務(wù),支持.NET Framework 、.NET ?CORE、 Mono 平臺(tái)。
本著學(xué)習(xí)的態(tài)度,造了這個(gè)輪子,也是為了更好的了解各個(gè)框架的原理和有點(diǎn),還希望可以和大家多交流 。
GitHub:https://github.com/maxzhang1985/YOYOFx? Star下, 歡迎一起交流。?.NET Core 和 YOYOFx 的交流群:?214741894??
如果你覺得本文對(duì)你有幫助,請(qǐng)點(diǎn)擊“推薦”,謝謝。
?
轉(zhuǎn)載于:https://www.cnblogs.com/maxzhang1985/p/5974429.html
總結(jié)
以上是生活随笔為你收集整理的在ASP.NET Core使用Middleware模拟Custom Error Page功能的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue 基于网易云API的短信验证码登录
- 下一篇: 使用iai_kinect2标定kinec