如何让用 ASP.Net Core 2.0 编写的自定义异常处理程序在 ASP.Net Core 3.1 中工作?

How can I get a custom exception handler written in ASP.Net Core 2.0 to work in ASP.Net Core 3.1?

学习完 Pluralsight 课程(正确完成 .NET 日志记录:Erik Dahl 使用 Serilog 的一种自以为是的方法)后,我开始在自己的 ASP.Net Core 3.1 MVC 项目中实施类似的解决方案。作为概念的初始证明,我从课程中下载了他的完整示例代码,并将他的记录器 class 库集成到我的项目中,以查看它是否有效。

不幸的是,除了一个关键因素外,一切似乎都有效。在我项目的 Startup.cs 文件而不是 app.UseExceptionHandler("/Home/Error"); 的 Configure 方法中,我现在有 app.UseCustomExceptionHandler("MyAppName", "Core MVC", "/Home/Error"); - 理论上这是为了命中一些自定义中间件,传递一些额外的数据用于错误记录,然后表现得像正常的异常处理程序并命中错误处理路径。实际上,它不会命中错误处理路径,用户会看到浏览器的错误页面。

中间件代码的注释说这段代码是:

// based on Microsoft's standard exception middleware found here:
// https://github.com/aspnet/Diagnostics/tree/dev/src/
//         Microsoft.AspNetCore.Diagnostics/ExceptionHandler

此 link 不再有效。我找到了新的 link,但它在 GitHub 存档中,它没有告诉我任何有用的信息。

我知道 .Net Core 2.0 和 3.1 之间的路由工作方式发生了变化,但我不确定这些是否会导致我遇到的问题。我不认为问题出在下面从 Startup.cs 调用的代码中。

public static class CustomExceptionMiddlewareExtensions
    {
        public static IApplicationBuilder UseCustomExceptionHandler(
            this IApplicationBuilder builder, string product, string layer, 
            string errorHandlingPath)
        {
            return builder.UseMiddleware<CustomExceptionHandlerMiddleware>
                (product, layer, Options.Create(new ExceptionHandlerOptions
                {
                    ExceptionHandlingPath = new PathString(errorHandlingPath)
                }));
        }
    }

我认为问题很可能出在实际 CustomExceptionMiddleware.cs 下面的 Invoke 方法中:

public sealed class CustomExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ExceptionHandlerOptions _options;
        private readonly Func<object, Task> _clearCacheHeadersDelegate;
        private string _product, _layer;

        public CustomExceptionHandlerMiddleware(string product, string layer,
            RequestDelegate next,
            ILoggerFactory loggerFactory,
            IOptions<ExceptionHandlerOptions> options,
            DiagnosticSource diagSource)
        {
            _product = product;
            _layer = layer;

            _next = next;
            _options = options.Value;
            _clearCacheHeadersDelegate = ClearCacheHeaders;
            if (_options.ExceptionHandler == null)
            {
                _options.ExceptionHandler = _next;
            }
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                WebHelper.LogWebError(_product, _layer, ex, context);

                PathString originalPath = context.Request.Path;
                if (_options.ExceptionHandlingPath.HasValue)
                {
                    context.Request.Path = _options.ExceptionHandlingPath;
                }

                context.Response.Clear();
                var exceptionHandlerFeature = new ExceptionHandlerFeature()
                {
                    Error = ex,
                    Path = originalPath.Value,
                };

                context.Features.Set<IExceptionHandlerFeature>(exceptionHandlerFeature);
                context.Features.Set<IExceptionHandlerPathFeature>(exceptionHandlerFeature);
                context.Response.StatusCode = 500;
                context.Response.OnStarting(_clearCacheHeadersDelegate, context.Response);

                await _options.ExceptionHandler(context);

                return;
            }
        }

        private Task ClearCacheHeaders(object state)
        {
            var response = (HttpResponse)state;
            response.Headers[HeaderNames.CacheControl] = "no-cache";
            response.Headers[HeaderNames.Pragma] = "no-cache";
            response.Headers[HeaderNames.Expires] = "-1";
            response.Headers.Remove(HeaderNames.ETag);
            return Task.CompletedTask;
        }
    }

任何建议将不胜感激,在过去的几天里,我一直在尝试让这个工作无济于事,除了我自己的项目之外,我很想能够对 Pluralsight 课程发表评论,以便其他任何试图这样做的人避免他们经历与我一样的挣扎。

您可以尝试在自定义异常处理程序中间件中重置端点和路由值,如下所示。

try
{
    context.Response.Clear();

    context.SetEndpoint(endpoint: null);
    var routeValuesFeature = context.Features.Get<IRouteValuesFeature>();
    routeValuesFeature?.RouteValues?.Clear();

    var exceptionHandlerFeature = new ExceptionHandlerFeature()
    {
        Error = ex,
        Path = originalPath.Value,
    };

//...

更多信息,请查看github中ExceptionHandlerMiddleware的源代码:

https://github.com/dotnet/aspnetcore/blob/5e575a3e64254932c1fd4937041a4e7426afcde4/src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerMiddleware.cs#L107

我实际上推荐了一种比我最初在 .NET Logging Done Right 课程中展示的方法更简单的方法(该课程大部分是围绕 .NET Framework 构建的,ASP.NET Core 模块是在之后添加的原始出版物)。进行 ASP.NET Core 日志记录的更好课程是 ASP.NET Core 中较新的 Effective Logging。但不是简单地让您去另一门课程观看,请允许我回答您的问题。

我认为你应该使用 UseExceptionHandler(string path) 中间件。您可以自由地在错误代码(控制器或剃须刀页面代码)中记录异常。您可以在此代码库中具体看到这一点:

https://github.com/dahlsailrunner/aspnetcore-effective-logging

具体看BookClub.UI项目中的这些文件:

  • Startup.cs(Configure 方法)
  • Pages/Error.cshtml
  • Pages/Error.cshtml.cs

这将使您的自定义代码最少(总是一件好事)。

HTH