Web API 审计日志记录 [英] Web API audit logging

查看:23
本文介绍了Web API 审计日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要审核对我的 Web API 的日志调用,理想情况下我想使用一个属性,例如:

I need to audit log calls to my Web API, ideally I'd like to use an Attribute, something like:

    [HttpPost, Auditing]
    public dynamic MyAPICall()

属性应该能够在执行前后拦截 API 调用,以便记录参数以及 API 调用运行所需的时间.

The Attribute should be able to intercept the API call before and after execution in order to log the parameters and also, how long the API call took to run.

使用 MVC,我可以创建一个 ActionFilterAttribute 派生类并覆盖 OnActionExecuted 和 OnActionExecuting.

With MVC I could create an ActionFilterAttribute derivative and override OnActionExecuted and OnActionExecuting.

Web API 世界中是否有等价物?

Is the equivalent possible in the Web API world?

推荐答案

我会使用消息处理程序而不是属性.

I would use a message handler rather than attributes.

public class LoggingHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        LogRequest(request);

        return base.SendAsync(request, cancellationToken).ContinueWith(task =>
        {
            var response = task.Result;

            LogResponse(response);

            return response;
        });
    }

    private void LogRequest(HttpRequestMessage request)
    {
        (request.Content ?? new StringContent("")).ReadAsStringAsync().ContinueWith(x =>
        {
            Logger.Info("{4:yyyy-MM-dd HH:mm:ss} {5} {0} request [{1}]{2} - {3}", request.GetCorrelationId(), request.Method, request.RequestUri, x.Result, DateTime.Now, Username(request));
        });
    }

    private void LogResponse(HttpResponseMessage response)
    {
        var request = response.RequestMessage;
        (response.Content ?? new StringContent("")).ReadAsStringAsync().ContinueWith(x =>
        {
            Logger.Info("{3:yyyy-MM-dd HH:mm:ss} {4} {0} response [{1}] - {2}", request.GetCorrelationId(), response.StatusCode, x.Result, DateTime.Now, Username(request));
        });
    }

    private string Username(HttpRequestMessage request)
    {
        var values = new List<string>().AsEnumerable();
        if (request.Headers.TryGetValues("my-custom-header-for-current-user", out values) == false) return "<anonymous>";

        return values.First(); 
    }
}

这篇关于Web API 审计日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆