The following code can be used to log inncomming and outgoing messages
public abstract class MessageHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var corrId =string.Format("{0}{1}", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId);
return request.Content.ReadAsByteArrayAsync()
.ContinueWith(t => IncommingMessageAsync(corrId, t.Result)
.ContinueWith(t2 => base.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
task.Result.Content.ReadAsByteArrayAsync()
.ContinueWith(t3 => OutgoingMessageAsync(corrId, t3.Result),cancellationToken);
return task.Result;
},cancellationToken),
cancellationToken)
.Unwrap())
.Unwrap();
}
protected abstract Task IncommingMessageAsync(string correlationId, byte[] message);
protected abstract Task OutgoingMessageAsync(string correlationId, byte[] message);
}
public class MessageLoggingHandler : MessageHandler
{
protected override Task IncommingMessageAsync(string correlationId, byte[] message)
{
var tcs = new TaskCompletionSource<object>();
Debug.WriteLine(string.Format("{0} - Incomming messages: {1}", correlationId, Encoding.UTF8.GetString(message)));
tcs.SetResult(null);
return tcs.Task;
}
protected override Task OutgoingMessageAsync(string correlationId, byte[] message)
{
var tcs = new TaskCompletionSource<object>();
Debug.WriteLine(string.Format("{0} - Outgoing messages: {1}", correlationId, Encoding.UTF8.GetString(message)));
tcs.SetResult(null);
return tcs.Task;
}
}
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
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


961
0




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