Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

c# - Web API audit logging

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()

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.

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

Is the equivalent possible in the Web API world?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Http message handler should be a good extensible point for such purposes. Be careful though, there can be some issues with concurrent request content reading. For instance, Model Binder may try to read request content while LoggingHandler is reading it and fail to deserialize a model. To prevent such issues just add Wait call to the LogRequestLoggingInfo method.

public class LoggingHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Log the request information
        LogRequestLoggingInfo(request);

        // Execute the request
        return base.SendAsync(request, cancellationToken).ContinueWith(task =>
        {
            var response = task.Result;
            // Extract the response logging info then persist the information
            LogResponseLoggingInfo(response);
            return response;
        });
    }

    private void LogRequestLoggingInfo(HttpRequestMessage request)
    {
        if (request.Content != null)
        {
            request.Content.ReadAsByteArrayAsync()
                .ContinueWith(task =>
                    {
                        var result = Encoding.UTF8.GetString(task.Result);
                        // Log it somewhere
                    }).Wait(); // !!! Here is the fix !!!
        }
    }

    private void LogResponseLoggingInfo(HttpResponseMessage response)
    {
        if (response.Content != null)
        {
            response.Content.ReadAsByteArrayAsync()
                .ContinueWith(task =>
                {
                    var responseMsg = Encoding.UTF8.GetString(task.Result);
                    // Log it somewhere
                });
        }
    }
}

You can read more about it here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...