净核心项目。我正在使用 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 的正确方法是什么。有人可以帮助我吗?任何帮助,将不胜感激。谢谢