instead of adding registration codes in each method, I create a MessageLoggingHandler, which can be registered in Global.asax.cs once, and then logs each request and response.
Here is the code that I use, you can change according to your requirements:
First create a MessageHandler class that inherits from DelegationHandler:
public abstract class MessageHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var corrId = Guid.NewGuid(); var requestMethod = request.Method.Method.ToString(); var requestUri = request.RequestUri.ToString(); var ipAddress = request.GetOwinContext().Request.RemoteIpAddress; var requestMessage = await request.Content.ReadAsByteArrayAsync(); await LogMessageAsync(corrId, requestUri, ipAddress, "Request", requestMethod, request.Headers.ToString(), requestMessage, string.Empty); var response = await base.SendAsync(request, cancellationToken); var responseMessage = await response.Content.ReadAsByteArrayAsync(); await LogMessageAsync(corrId, requestUri, ipAddress, "Response", requestMethod, response.Headers.ToString(), responseMessage, ((int)response.StatusCode).ToString() + "-" + response.ReasonPhrase); return response; } protected abstract Task LogMessageAsync(Guid CorrelationId, string APIUrl, string ClientIPAddress, string RequestResponse, string HttpMethod, string HttpHeaders, byte[] HttpMessage, string HttpStatusCode); } public class MessageLoggingHandler : MessageHandler { protected override async Task LogMessageAsync(Guid CorrelationId, string APIUrl, string ClientIPAddress, string RequestResponse, string HttpMethod, string HttpHeaders, byte[] HttpMessage, string HttpStatusCode) {
Then, in your Global.asax.cs file, you need to register the MessageLoggingHandler created above:
GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageLoggingHandler());
Just keep in mind that this will log every request and response, there will be a full message. This can take up a lot of space very quickly (depending on the use of the API). Therefore, you may need to configure it (for example, keep records for a month or so or ignore 200-OK responses, etc.)