Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Thursday, December 16, 2021

Log message Request and Response in ASP.NET WebAPI

There are multiple approaches to generically handle Request/Response logging for every WebAPI method calls:

1.    ActionFilterAttribute: One can write custom ActionFilterAttribute and decorate the controller/action methods to enable logging.

Con: You need to decorate every controller/methods (still you can do it on base controller, but still it doesn't address cross cutting concerns.

2.    Override BaseController and handle logging there.

Con: We are expecting/forcing the controllers to inherit from a custom base controller.

3.    Using DelegatingHandler.

Advantage: We are not touching controller/method here with this approach. Delegating handler sits in isolation and gracefully handles the request/response logging.



I would recommend using a DelegatingHandler. Then you will not need to worry about any logging code in your controllers.

public class LogRequestAndResponseHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content != null)
        {
            // log request body
            string requestBody = await request.Content.ReadAsStringAsync();
            Trace.WriteLine(requestBody);
        }
        // let other handlers process the request
        var result = await base.SendAsync(request, cancellationToken);

        if (result.Content != null)
        {
            // once response body is ready, log it
            var responseBody = await result.Content.ReadAsStringAsync();
            Trace.WriteLine(responseBody);
        }

        return result;
    }
}

Just replace Trace.WriteLine with your logging code and register the handler in WebApiConfig like this:



For more indepth article, refer this http://weblogs.asp.net/fredriknormen/log-message-request-and-response-in-asp-net-webapi


No comments:

Post a Comment