自定义中间件调用日志

问题描述 投票:0回答:1

我有一个用于错误处理的以下自定义中间件

public static class ErrorHandlerExtensions
{
    public static void UseErrorHandler(this IApplicationBuilder app)
    {
        app.UseExceptionHandler(appError =>
        {
            appError.Run(async context =>
            {
                var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
                if (contextFeature == null) return;

                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                context.Response.ContentType = "application/json";

                context.Response.StatusCode = contextFeature.Error switch
                {
                    BadRequestException => (int)HttpStatusCode.BadRequest,
                    OperationCanceledException => (int)HttpStatusCode.ServiceUnavailable,
                    NotFoundException => (int)HttpStatusCode.NotFound,
                    _ => (int)HttpStatusCode.InternalServerError
                };

                var errorResponse = new
                {
                    statusCode = context.Response.StatusCode,
                    message = contextFeature.Error.GetBaseException().Message
                };

                await context.Response.WriteAsync(JsonSerializer.Serialize(errorResponse));
            });
        });
    }
}

我也想在这里添加记录器。正如我们所知,由于它是一个静态类,我们不能声明只读并将其传递到构造函数中。

我应该做什么?

我尝试像往常一样添加记录器-

public static class ErrorHandlerExtension
{
    private static readonly ILogger _logger;
        public static void UseErrorHandler(this IApplicationBuilder app, ILogger logger)
{
logger= _logger;
}

但是它按照预期给出了错误

c# asp.net-core .net-core middleware ilogger
1个回答
0
投票

我也想在这里添加记录器。正如我们所知,由于它是一个静态类,我们不能声明只读并将其传递到构造函数中。我应该做什么?

您可以使用 IApplicationBuilder.ApplicationServices.GetRequiredService 方法获取所需的服务。

更多详情,您可以参考以下测试代码:

{ 应用程序.UseExceptionHandler(应用程序错误=> { appError.Run(异步上下文=> { var loggerFactory = app.ApplicationServices.GetRequiredService(); var _logger = loggerFactory.CreateLogger();

           _logger.LogError("test");
           var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
           if (contextFeature == null) return;

           context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
           context.Response.ContentType = "application/json";

           //context.Response.StatusCode = contextFeature.Error switch
           //{
           //    BadRequestException => (int)HttpStatusCode.BadRequest,
           //    OperationCanceledException => (int)HttpStatusCode.ServiceUnavailable,
           //    NotFoundException => (int)HttpStatusCode.NotFound,
           //    _ => (int)HttpStatusCode.InternalServerError
           //};

           var errorResponse = new
           {
               statusCode = context.Response.StatusCode,
               message = contextFeature.Error.GetBaseException().Message
           };

           await context.Response.WriteAsync(JsonSerializer.Serialize(errorResponse));
       });
   });

结果:

© www.soinside.com 2019 - 2024. All rights reserved.