DelegatingHandler for response in WebApi

Halvard picture Halvard · Aug 15, 2012 · Viewed 44.6k times · Source

I am currently using several delegation handlers (classes derived from DelegatingHandler) to work on the request before it is sent, for things like validating a signature etc. This is all very nice, because I don't have to duplicate signature validation on all calls (for example).

I would like to use the same principle on the response from the same web request. Is there something similar to the DelegatingHandler for the response? A way to catch the response before it has returned to the method, in a way?

Additional information: I am calling a web api using HttpClient.PutAsync(...)

Answer

Aliostad picture Aliostad · Aug 15, 2012

Yes. You can do that in the continuation task.

I explain it here.

For example, this code (from the blog above) traces request URI and adds a dummy header to response.

public class DummyHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // work on the request 
       Trace.WriteLine(request.RequestUri.ToString());

       var response = await base.SendAsync(request, cancellationToken);
       response.Headers.Add("X-Dummy-Header", Guid.NewGuid().ToString());
       return response;
    }
}