Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DelegatingHandler for response in WebApi

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(...)

like image 770
Halvard Avatar asked Aug 15 '12 13:08

Halvard


People also ask

How do I create a response in Web API?

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response. Convert directly to an HTTP response message. Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. Write the serialized return value into the response body; return 200 (OK).

Can we return view from ASP Net Web API?

Solution 1. You don't. You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page.

Why are the Frombody and FromUri attributes needed in asp net Web API?

When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding. In order to bind a model (an action parameter), that would normally default to a formatter, from the URI we need to decorate it with [FromUri] attribute.

What is HttpClientHandler C#?

The HttpClient class uses a message handler to process the requests on the client side. The default handler provided by the dot net framework is HttpClientHandler. This HTTP Client Message Handler sends the request over the network and also gets the response from the server.


1 Answers

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;     } } 
like image 64
Aliostad Avatar answered Sep 21 '22 06:09

Aliostad