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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值