Steps to write a custom message handler: derive from System.Net.Http.DelegatingHandler and override theSendAsync method. This method has the following signature:
Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken);
The method takes an HttpRequestMessage as input and asynchronously returns an HttpResponseMessage. A typical implementation does the following:
- Process the request message.
- Call
base.SendAsync
to send the request to the inner handler. - The inner handler returns a response message. (This step is asynchronous.)
- Process the response and return it to the caller.
Here is a trivial example:
public class MessageHandler1 : DelegatingHandler { protected async override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { Debug.WriteLine("Process request"); // Call the inner handler. var response = await base.SendAsync(request, cancellationToken); Debug.WriteLine("Process response"); return response; } }