Skip to content

.NET Core 使用 Filter 记录请求的参数和返回值

🏷️ .NET Core

主要参考了官方的 MSDN 文档 Filters in ASP.NET Core 和 官方的 Sample 代码 FiltersSample

过滤器继承了接口 IActionFilterIResultFilter

IActionFilter 包含 OnActionExecutingOnActionExecuted 方法。
IResultFilter 包含 OnResultExecutingOnResultExecuted 方法。

csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

/// <summary>
/// 记录日志用过滤器
/// </summary>
public class LogstashFilter : IActionFilter, IResultFilter
{
    /// <summary>
    /// Action 调用前执行
    /// </summary>
    /// <param name="context"></param>
    public void OnActionExecuting(ActionExecutingContext context)
    {
        ParameterLogEntity logEntity = new ParameterLogEntity()
        {
            Signature = context.ActionDescriptor.DisplayName
        };

        foreach (var arg in context.ActionArguments)
        {
            logEntity.Args.Add($"{arg.Key} : {JsonHelper.SerializeObject(arg.Value)}");
        }

        LogstashHelper.Log(logEntity);
    }

    /// <summary>
    /// Action 方法调用后,Result 方法调用前执行
    /// </summary>
    /// <param name="context"></param>
    public void OnActionExecuted(ActionExecutedContext context)
    {
        // do nothing
    }

    /// <summary>
    /// Result 方法调用前(View 呈现前)执行
    /// </summary>
    /// <param name="context"></param>
    public void OnResultExecuting(ResultExecutingContext context)
    {
        // do nothing
    }

    /// <summary>
    /// Result 方法调用后执行
    /// </summary>
    /// <param name="context"></param>
    public void OnResultExecuted(ResultExecutedContext context)
    {
        if (context.Result is ObjectResult)
        {
            ResultLogEntity logEntity = new ResultLogEntity()
            {
                Result = JsonHelper.SerializeObject(((ObjectResult)context.Result).Value)
            };

            LogstashHelper.Log(logEntity);
        }
    }
}

Startup.cs 中增加全局的过滤器。

csharp
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // ...
    //配置 mvc
    services.AddMvc(options => {
        options.Filters.Add(new LogstashFilter());
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    // ...
}

参考

  1. MVC 之 自定义过滤器 (ActionFilterAttribute) 这篇博客写的是 .NET MVC,.NET Core 也有相同的类
  2. MVC 学习笔记:MVC 实现用户登录验证 ActionFilterAttribute 用法并实现统一授权
  3. ASP.NET Core 中读取 Request.Body 的正确姿势
  4. Reading request body in ASP.NET Core
  5. ASP.NET Core 中间件(Middleware)详解
  6. ASP.NET Core 中间件
  7. 将 HTTP 处理程序和模块迁移到 ASP.NET Core 中间件
  8. ASP.NET Core 中间件 中间件(Middleware)和过滤器(Filter)的区别
  9. Filters in ASP.NET Core
  10. FiltersSample