网页API审核日志 [英] Web API audit logging

查看:186
本文介绍了网页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(); 
    }
}

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

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