-1

净核心项目。我正在使用 Azure 应用程序洞察力进行日志记录。我在 services.AddApplicationInsightsTelemetry(); 中添加了以下行 在我的startup.cs中。在控制器和业务层中,我将通过依赖注入获得 ILogger。但我想出了一些不同的东西。我创建了 ApiExceptionFilter,代码如下所示。

public class ApiExceptionFilter : ExceptionFilterAttribute
    {  
        public override void OnException(ExceptionContext context)
        {
            ApiError apiError = null;
            if (context.Exception is ApiException)
            {
                // handle explicit 'known' API errors
                var ex = context.Exception as ApiException;
                context.Exception = null;
                apiError = new ApiError(ex.Message);

                context.HttpContext.Response.StatusCode = ex.StatusCode;
            }
            else if (context.Exception is UnauthorizedAccessException)
            {
                apiError = new ApiError("Unauthorized Access");
                context.HttpContext.Response.StatusCode = 401;

                // handle logging here
            }
            else if (context.Exception is NotImplementedException)
            {
                apiError = new ApiError("Not Implemented");
                context.HttpContext.Response.StatusCode = 401;

                // handle logging here
            }
            else if (context.Exception is ArgumentNullException)
            {
                apiError = new ApiError(string.Format("Parameter: {0} is required, it cannot be empty", (context.Exception as ArgumentNullException).ParamName));
                context.HttpContext.Response.StatusCode = 401;

                // handle logging here
            }
            else
            {
                // Unhandled errors
                var msg = context.Exception.GetBaseException().Message;
                string stack = context.Exception.StackTrace;
                apiError = new ApiError(msg);
                apiError.detail = stack;

                context.HttpContext.Response.StatusCode = 500;

                // handle logging here
            }

            // always return a JSON result
            context.Result = new JsonResult(apiError);

            base.OnException(context);
        }
    }

但在这里我不能做类似的事情

private readonly ILogger _logger;
        public ApiExceptionFilter(ILogger logger)
        {
            _logger = logger;
        }

如果我进行上述更改,那么

  [ApiController]
    [ApiExceptionFilter] //here it asking for paramter ilogger
    public class MyController : ControllerBase

在上面的代码中 [ApiExceptionFilter] 它会要求我传递 ILogger 参数。

我只是想知道在 ApiExceptionFilter 中添加 ILogger 的正确方法是什么。有人可以帮助我吗?任何帮助,将不胜感激。谢谢

4

2 回答 2

2

您可以添加您的异常过滤器:

[TypeFilter(typeof(ApiExceptionFilter))]

这将允许您的过滤器使用来自 DI 容器的服务,因为框架将在请求时创建过滤器。

例如

public class ApiExceptionFilter : ExceptionFilterAttribute
{
    public ApiExceptionFilter(ILogger logger)
    {
        // Assign the logger to a field etc.
    }
}

您还可以[ServiceFilter(typeof(ApiExceptionFilter))]在 DI 容器中使用和注册过滤器本身。

于 2020-08-19T06:38:12.417 回答
1

为了在动作过滤器中使用 DependencyInjection,您需要使用 TypeFilterAttribute,

例子:

public class HandleExceptionAttribute : TypeFilterAttribute
{
        public HandleExceptionAttribute() : base(typeof(HandleExceptionPrivate))
        {
        }

        class HandleExceptionPrivate : ExceptionFilterAttribute
        {
            private readonly ILogger _logger;
            private readonly IHostingEnvironment _env;
          
            public HandleExceptionPrivate(ILoggerFactory logger, IHostingEnvironment env)
            {
                _logger = logger.CreateLogger("Exeption Filter");
                _env = env;
            }

            public override void OnException(ExceptionContext context)
            {
                _logger.LogError(Constants.LoggingEvents.EXCEPTION, context.Exception, "message");
               
                context.ExceptionHandled = true;
                context.Exception = null;
            }
        }
}
于 2020-08-19T06:41:34.087 回答