Webapi 日志过滤器(接口日志记录)

文章描述了一个名为LogFilter的类,它是一个异步Action过滤器,用于处理API请求时的日志记录、参数验证和根据不同请求方法返回适当响应。它在POST、PUT、DELETE请求中记录详细信息,而在GET请求和其他非标准方法下提供错误处理。
摘要由CSDN通过智能技术生成
/// <summary>
/// 日志过滤器
/// </summary>
public class LogFilter : IAsyncActionFilter
{
    private readonly ILogger<LogFilter> _logger;

    public LogFilter(
        ILogger<LogFilter> logger
        )
    {
        _logger = logger;
    }
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var contentType = "application/json";

        //校验参数
        if (!context.ModelState.IsValid)
        {
            context.Result = new ContentResult()
            {
                Content = context.ModelState.Values.SelectMany(e => e.Errors).Select(e => e.ErrorMessage).FirstOrDefault(),
                StatusCode = 500,
                ContentType = contentType
            };
        }

        var apiPath = context.HttpContext.Request.Path.ToString();//获得调用接口,
        var RequestType = context.HttpContext.Request.Method;
        string arguments = JsonSerializer.Serialize(context.ActionArguments);

        //参数读取
        if (RequestType == "POST" || RequestType == "PUT" || RequestType == "DELETE")
        {
            _logger.LogInformation($"请求方式:{RequestType},接口:{apiPath},请求参数:{arguments}");

            //具体业务,  如果要不进入Action给ActionExecutingContext 对象的Result复制.
            context.Result = new ContentResult()
            {
                Content = "成功了. ",
                StatusCode = 200,
                ContentType = contentType
            };
        }
        else if (RequestType == "GET")
        {
            _logger.LogInformation($"请求方式:{RequestType},接口:{apiPath},请求参数:{arguments}");
        }
        else
        {
            context.Result = new ContentResult()
            {
                Content = "请求方式错误!",
                StatusCode = 405,
                ContentType = contentType
            };
        }

        var executedContext = await next();
        Console.WriteLine("Result:" + JsonSerializer.Serialize(executedContext.Result));
    }
}
builder.Services.AddMvc(option =>
{
    option.Filters.Add(typeof(LogFilter));
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值