What is Delegating Handler?

Technology CommunityCategory: ASP.NET Web APIWhat is Delegating Handler?
VietMX Staff asked 3 years ago

message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.

Typically, a series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain. This pattern is called a delegating handler.

Consider:

public class DateObsessedHandler : DelegatingHandler
{          
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, 
        CancellationToken cancellationToken)
    {
        var requestDate = request.Headers.Date;
        // do something with the date ...
         
        var response =  await base.SendAsync(request, cancellationToken);
 
        var responseDate = response.Headers.Date;
        // do something with the date ...
 
        return response;
    }
}

// ...
GlobalConfiguration.Configuration
                   .MessageHandlers
                   .Add(new DateObsessedHandler());