如何在 ASP.NET Core WebAPI 中将 ILogger 添加到 GlobalErrorHandling

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

我有我的例外处理程序:

    public class ApplicationExceptionHandler :ExceptionFilterAttribute
    {
        public ApplicationExceptionHandler()
        {
        }
        public override void OnException(ExceptionContext context)
        {
            ApiError apiError = null;
            switch (context.Exception)
            {
                case  TaxiNotFoundException:
                    apiError = new ApiError(context.Exception.Message);
                    context.Result = new ObjectResult(apiError) {StatusCode = StatusCodes.Status404NotFound };
                    break;
                default:
                    context.Result = new BadRequestResult();
                    break;
            }
            base.OnException(context);
        }
    }

   public class ApiError
    {
        public string Message { get; set; }
        public ApiError(string message)
        {
            Message = message;
        }
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }
    }

    [ApplicationExceptionHandler]
    public class TaxisController : ControllerBase
    { ...

如何在异常处理程序中使用ILogger?如果我制作一个构造函数:

public ApplicationExceptionHandler(ILogger<ApplicationExceptionHandler> logger)
{
    this.logger = logger;
}

在我的控制器中,我收到编译器异常:

[ApplicationExceptionHandler (ILogger < ApplicationExceptionHandler > logger)]

Logger 是一种在此上下文中无效的类型。如何将 ILogger 添加到异常处理程序?

c# asp.net-core exception asp.net-core-webapi
1个回答
1
投票

确定控制器属性的语法:

    [TypeFilter(typeof(ApplicationExceptionHandler))]

以及异常处理程序:

    public class ApplicationExceptionHandler :ExceptionFilterAttribute
    {
        private readonly ILogger<ApplicationExceptionHandler> logger;

        public ApplicationExceptionHandler(ILogger<ApplicationExceptionHandler> logger)
        {
            this.logger = logger;
        }
© www.soinside.com 2019 - 2024. All rights reserved.