ASP.NET Core中显示自定义错误页面-增强版
生活随笔
收集整理的這篇文章主要介紹了
ASP.NET Core中显示自定义错误页面-增强版
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
之前的博文?ASP.NET Core中顯示自定義錯誤頁面?中的方法是在項目中硬編碼實現的,當有多個項目時,就會造成不同項目之間的重復代碼,不可取。
在這篇博文中改用middleware實現,并且放在獨立的項目中發布成NuGet包,項目中使用時只需安裝NuGet包,然后在Startup的Configure()方法中添加如下的一行代碼。
app.UseCustomErrorPages();CustomErrorPagesMiddleware的實現代碼如下:
public class CustomErrorPagesMiddleware {private readonly RequestDelegate _next;private readonly ILogger _logger;public CustomErrorPagesMiddleware(RequestDelegate next,ILoggerFactory loggerFactory){_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 (statusCode == 404 || statusCode == 500){await ErrorPage.ResponseAsync(context.Response, statusCode);}}} }ErrorPage的實現代碼如下:
public static class ErrorPage {public static async Task ResponseAsync(HttpResponse response, int statusCode){if (statusCode == 404){await response.WriteAsync(Page404);}else if (statusCode == 500){await response.WriteAsync(Page500);}}private static string Page404 => @"html...";private static string Page500 => @"html..."; }CustomErrorPagesExtensions的實現代碼如下:
public static class CustomErrorPagesExtensions {public static IApplicationBuilder UseCustomErrorPages(this IApplicationBuilder app){if (app == null){throw new ArgumentNullException(nameof(app));}return app.UseMiddleware<CustomErrorPagesMiddleware>();} }代碼參考自:
1)CustomErrorPagesMiddleware.cs
2)DeveloperExceptionPageMiddleware.cs
總結
以上是生活随笔為你收集整理的ASP.NET Core中显示自定义错误页面-增强版的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Storm学习二
- 下一篇: Java编程的逻辑 (59) - 文件和