如何在.Net WebAPI中禁用来自外部源的ExceptionFilterAttribute

z18hc3ub  于 2023-03-20  发布在  .NET
关注(0)|答案(1)|浏览(94)

我有来自外部源的ExceptionFilterAttribute(图书馆)。我想用这个图书馆,因为它的功能远不止这些。但它会过滤日志记录(错误级别)。我不想对业务异常使用错误级别。当请求出现业务异常时,我将抛出该错误级别(与400响应代码)。我怎么能禁用这个过滤器与specific异常。我只是想与业务异常的信息级别日志

public class GlobalExceptionFilter : ExceptionFilterAttribute
  {
    private readonly ILogger<GlobalExceptionFilter> _logger;

    public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) => this._logger = logger;

    public override void OnException(ExceptionContext context)
    {
      this._logger.LogError(context.Exception, context.Exception?.Message);
      ...
    }
  }

我尝试使用serviceDecorator删除此ExceptionFilter,但无法成功。因为每个请求都调用筛选器的构造函数。因此,我无法在启动时删除

s5a0g9ez

s5a0g9ez1#

您可以利用模式匹配来获得此结果
我重写了你的过滤器来检查异常是不是HttpRequestException还是一个非400 HTTP错误。你可以根据你想要过滤的具体条件定制检查(因为我不知道你过滤的具体类型)

public class GlobalExceptionFilter : ExceptionFilterAttribute
{
    private readonly ILogger<GlobalExceptionFilter> _logger;

    public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) => this._logger = logger;

    public override void OnException(ExceptionContext context)
    {
        // Log if we have an exception other than a HttpRequestException or if we have an exception other than HTTP 400
        if (context.Exception is not HttpRequestException ex || (int)(ex.StatusCode ?? HttpStatusCode.InternalServerError) != 400)
            _logger.LogError(context.Exception, context.Exception.Message);
    }
}

考虑以下MVC端点

using System.Net;
using System.Runtime.InteropServices;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication6.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ValuesController : ControllerBase
    {
        [HttpGet, Route(nameof(GetLoggableValues))]
        public IActionResult GetLoggableValues()
        {
            // Logs
            throw new HttpRequestException("TEST", null, HttpStatusCode.BadGateway);
        }

        [HttpGet, Route(nameof(GetLoggableValues2))]
        public IActionResult GetLoggableValues2()
        {
            // Logs
            throw new SEHException("TEST2");
        }

        [HttpGet, Route(nameof(GetNonLoggableValues))]
        public IActionResult GetNonLoggableValues()
        {
            // Does not log
            throw new HttpRequestException("TEST3", null, HttpStatusCode.BadRequest);
        }

        [HttpGet, Route(nameof(GetNonLoggableValues2))]
        public IActionResult GetNonLoggableValues2()
        {
            // Does not log, even if we hide that it is a HttpRequestException
            Exception ex = new HttpRequestException("TEST4", null, HttpStatusCode.BadRequest);
            throw ex;
        }
    }
}

第一个将记录为HTTP 502错误。第二个将记录为不是HttpRequestException。第三个和第四个都是具有HTTP 400状态代码的HttpRequestException,不会记录。

相关问题