The following code can be used to log inncomming and outgoing messages
public abstract class MessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var corrId = string.Format("{0}{1}", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId);
var result = await request.Content.ReadAsByteArrayAsync();
await IncommingMessageAsync(corrId, result);
var response = await base.SendAsync(request, cancellationToken);
byte[] responseMessage;
if (response.IsSuccessStatusCode)
responseMessage = await response.Content.ReadAsByteArrayAsync();
else
responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);
await OutgoingMessageAsync(corrId, responseMessage);
return response;
}
protected abstract Task IncommingMessageAsync(string correlationId, byte[] message);
protected abstract Task OutgoingMessageAsync(string correlationId, byte[] message);
}
public class MessageLoggingHandler : MessageHandler
{
protected override async Task IncommingMessageAsync(string correlationId, byte[] message)
{
await Task.Run(() =>
Debug.WriteLine(string.Format("{0} - Incomming messages: {1}", correlationId, Encoding.UTF8.GetString(message))));
}
protected override async Task OutgoingMessageAsync(string correlationId, byte[] message)
{
await Task.Run(() =>
Debug.WriteLine(string.Format("{0} - Outgoing messages: {1}", correlationId, Encoding.UTF8.GetString(message))));
}
}
The MessageHandler need to be registered to be used, it can be done in the global.asax:
GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageLoggingHandler());
Note: Because the messages is read into a buffer, there will be two compy of the data, so be carefull when it comes to large messages.
Fork
2 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


866
0




Mark '.net4.5' tag as 'like'
Mark '.net4.5' tag as 'ignore'