【问题标题】:.NET Core: access request data on bad request when ApiController shortcuts the pipeline.NET Core:当 ApiController 缩短管道时访问错误请求的请求数据
【发布时间】:2019-08-08 17:14:08
【问题描述】:

对于所有这些在日志记录问题上的绊脚石,我在Github 上创建了一个小型公共游乐场。欢迎加入。


我仍在尝试针对我的请求使用点击所有日志过滤器。

目标很简单。不是在每个控制器方法中编写日志,而是在过滤器(或中间件)中实现它们一次,然后将它们全局应用于所有控制器。这在出现问题时使用。我可以查看导致问题的数据。

例如一个控制器动作(使用全局应用的过滤器)

[HttpPut("{id:int}")
public IActionResult UpdateModel(int id, [FromBody] MyRequestModel request) {}

会创建类似的日志

[Timestamp] INFO: MyNamespace.Controllers.MyModelController.UpdateModel
{ 
  "Parameters": {
     "Id": 1,
     "Request": {
       "Name": "abc",
       "SomeInt": 3
     }
  }
}

漂亮,不再需要在每个方法中手动记录。

但是等等:它是一个 API,我使用了 [ApiController] 属性,并且请求模型包含无效数据(假设 Name = "a" 但它的长度至少需要为 3)。

这给了我 3 个问题

  1. ActionFilter.OnActionExecuting 是快捷方式,不会被调用(由于 ApiController)
  2. 似乎跳过了参数的绑定,绑定的(无效)数据未应用于 ActionArguments
  3. 仅调用了 ResultFilter.OnResultExecuted,但似乎无法访问/记录无效数据

这在某种程度上意味着日志记录只有在一切顺利时才有效,但最有趣的日志不是那些出现问题的日志吗?

public void OnActionExecuting(ActionExecutingContext context)
  {
    _loggerFactory
    .CreateLogger(context.ActionDescriptor.DisplayName.Split(" ")[0])
    .LogInformation
    (
      JsonConvert.SerializeObject
      (
        new { Parameters = context.ActionArguments },
        Formatting.Indented
      )
    );
  }

第 1 点:我当然可以从每个控制器中删除 ApiController 并返回手动返回 BadRequest 结果。但我喜欢集中式方法,并愿意坚持下去。

我喜欢模型绑定方法,它为我提供了用于序列化日志的类(而不是手动将请求正文作为一个字符串读取)。使用自定义 Json 合约解析器,我可以将模型属性标记为敏感,并将它们隐藏在日志中(对于那些关心安全性的人)。

所以我的实际问题:

有没有办法在 ResultFilter 中获取模型绑定值,或者它们是否被完全丢弃? 或者有没有办法挂钩模型绑定/模型验证并在它们被扔掉之前在那里写日志? 两者都特别适用于 ApiController 属性开始缩短过滤器管道的情况。


public class LogFilter : IActionFilter, IResultFilter, IExceptionFilter
{

    private readonly ILoggerFactory _loggerFactory;

    public LogFilter(ILoggerFactory loggerFactory)
    {
      _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
      _loggerFactory
         .CreateLogger(context.ActionDescriptor.DisplayName.Split(" ")[0])
         .LogInformation
         (
           JsonConvert.SerializeObject
           (
             new
             {
               RequestBody = ReadBodyAsString(context.HttpContext.Request),
               Parameter = context.ActionArguments
             },
             Formatting.Indented
           )
         );
    }

    public void OnActionExecuted(ActionExecutedContext context) {}      

    public void OnResultExecuting(ResultExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
          _loggerFactory
            .CreateLogger(context.ActionDescriptor.DisplayName.Split(" ")[0])
            .LogWarning
            (
               JsonConvert.SerializeObject
               (
                 new
                 {
                   RequestBody = ReadBodyAsString(context.HttpContext.Request),
                   ModelErrors = context.ModelState
                    .Where(kvp => kvp.Value.Errors.Count > 0)
                    .ToDictionary
                    (
                      kvp => kvp.Key,
                      kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
                    )
                 },
                 Formatting.Indented
               )
            );
        }
    }

    public void OnResultExecuted(ResultExecutedContext context) {}

    public void OnException(ExceptionContext context)
    {

        _loggerFactory
        .CreateLogger(context.ActionDescriptor.DisplayName.Split(" ")[0])
        .LogError
        (
          context.Exception,
          JsonConvert.SerializeObject
          (
            new
            {
              //RequestBody = ReadBodyAsString(context.HttpContext.Request) // body is disposed here
            },
            Formatting.Indented
          )
        );

    }
}

【问题讨论】:

  • 您确定您使用的是System.Web.Http.Filters.ActionFilterAttribute 而不是System.Web.Mvc.ActionFilterAttribute?注意命名空间。
  • 我不会说它们,因为我从 Microsoft.AspNetCore.Mvc.Filters 命名空间实现了接口 IActionFilter 和 IResultFilter。
  • 啊,对,.NET Core。我的错。

标签: c# asp.net-core .net-core asp.net-core-webapi .net-core-2.2


【解决方案1】:

您可以创建一个实现 IActionFilter 的 OnActionExecuting 方法的类。并将其注册到全局过滤器中,以便它适用于所有控制器和操作。当模型绑定(因为长度)发生异常时,即使使用 [ApiController] 仍然会调用您的 OnActionExecuting 方法并且您可以将其记录在那里。

例如。

public class MyActionFilterAttribute: IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        //Your logic to log the request, you can get the details from
        //context parameter

        //You can check if model state is valid also by using the property
        //context.ModelState.IsValid
    }
}

在 Startup.cs 中,您需要将 SuppressModelStateInvalidFilter 设置为 true。这不会自动返回 400 状态。您的控制器方法仍会被调用,并且由于您有操作过滤器,因此会调用 OnActionExecuting。

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(
            config =>
            {
                config.Filters.Add(new MyActionFilterAttribute());
            })
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });
    }

【讨论】:

  • 你确定吗?我对其进行了测试,并且 OnException 被调用以处理真正的异常(因为我用它来记录异常),但不适用于 ModelValidation 错误
  • @monty,验证后更新了答案。请立即检查。
  • 是的,将 SuppressModelStateInvalidFilter 设置为 true 将再次触发控制器操作并调用过滤器。但是随后又需要检查控制器中的无效模型状态(这不需要使用 ApiController 的美妙之处)。结帐方案 2 我的实验解决它:github.com/MontyGvMC/dot-net-core-logging-demo-api
  • 好吧,目前看来最好的方法是以正确的顺序将 suppressModelStateInvalidFilter 与第二个全局 BadRequestFilter 结合使用。所以两者都有好处(ApiController 的好处和集中式日志记录的好处)。
  • @monty,如前所述,目前唯一的方法是检查 ModelState.IsValid 并返回。我们可以向 Microsoft/开源贡献者请求一个功能,以提供一个过滤器,该过滤器仅在模型验证中出现任何错误时调用,即使使用 [ApiController] 也是如此。
【解决方案2】:

我认为你对 ActionFilter 只捕获成功的请求是正确的。 对于您的无效请求,也许您可​​以查看InvalidModelStateResponseFactory。

使用 options.InvalidModelStateResponseFactory 时,您可以读取模型和验证错误。

【讨论】:

  • puh,确实是一种可行的方法,但我正在思考如何在那里添加日志记录。
  • 有人遇到了同样的问题,解决了this way
  • 感谢您的链接。该代码帮助我完成了几个步骤。对于我打开此问题的最后步骤:github.com/aspnet/AspNetCore.Docs/issues/13720
猜你喜欢
  • 2022-09-30
  • 1970-01-01
  • 2020-05-15
  • 2013-12-10
  • 1970-01-01
  • 2023-03-28
  • 2017-07-20
  • 1970-01-01
  • 2020-05-02
相关资源
最近更新 更多