日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET Core中显示自定义错误页面-增强版

發(fā)布時(shí)間:2025/3/18 asp.net 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET Core中显示自定义错误页面-增强版 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

之前的博文?ASP.NET Core中顯示自定義錯(cuò)誤頁面?中的方法是在項(xiàng)目中硬編碼實(shí)現(xiàn)的,當(dāng)有多個(gè)項(xiàng)目時(shí),就會(huì)造成不同項(xiàng)目之間的重復(fù)代碼,不可取。

在這篇博文中改用middleware實(shí)現(xiàn),并且放在獨(dú)立的項(xiàng)目中發(fā)布成NuGet包,項(xiàng)目中使用時(shí)只需安裝NuGet包,然后在Startup的Configure()方法中添加如下的一行代碼。

app.UseCustomErrorPages();

CustomErrorPagesMiddleware的實(shí)現(xiàn)代碼如下:

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的實(shí)現(xiàn)代碼如下:

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的實(shí)現(xiàn)代碼如下:

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

總結(jié)

以上是生活随笔為你收集整理的ASP.NET Core中显示自定义错误页面-增强版的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。