Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to log asp.net webapi 2 request and response body to a database

I am using Microsoft Asp.net WebApi2 hosted on IIS. I very simply would like to log the request body (XML or JSON) and the response body for each post.

There is nothing special about this project or the controller processing the post. I am not interested in using logging frameworks like nLog, elmah, log4net, or the built-in tracing features of web API unless it is necessary to do so.

I am simply wanting to know where to put my logging code and how to get the actual JSON or XML from the incoming and outgoing request and response.

My controller post method:

public HttpResponseMessage Post([FromBody])Employee employee) {    if (ModelState.IsValid)    {       // insert employee into to the database    }  } 
like image 259
user2315985 Avatar asked May 14 '14 16:05

user2315985


People also ask

How do I log a response and request metadata in asp net Web API?

There are multiple ways to inject logging and other crosscutting concerns in Web API. One way is to create a custom ApiController class, or a base class for all of our controllers, and then override the ExecuteAsync method. Another way is to use a custom action filter.

How do I return HTTP response messages in Web API?

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response. Convert directly to an HTTP response message. Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. Write the serialized return value into the response body; return 200 (OK).

How do I send a custom response in Web API?

Implementing a custom response handler in Web API. Create a new Web API project in Visual Studio and save it with the name of your choice. Now, select the Web API project you have created in the Solution Explorer Window and create a Solution Folder. Create a file named CustomResponseHandler.


2 Answers

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:

config.MessageHandlers.Add(new LogRequestAndResponseHandler()); 

Here is the full Microsoft documentation for Message Handlers.

like image 56
SoftwareFactor Avatar answered Sep 23 '22 14:09

SoftwareFactor


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.

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

like image 44
Venkatesh Muniyandi Avatar answered Sep 24 '22 14:09

Venkatesh Muniyandi