AspNetCore.Docs/aspnet/web-api/overview/advanced/httpclient-message-handlers.md

3.1 KiB

uid title author description ms.author manager ms.date ms.topic ms.assetid ms.technology ms.prod msc.legacyurl msc.type
web-api/overview/advanced/httpclient-message-handlers HttpClient Message Handlers in ASP.NET Web API | Microsoft Docs MikeWasson aspnetcontent wpickett 10/01/2012 article 5a4b6c80-b2e9-4710-8969-d5076f7f82b8 dotnet-webapi .net-framework /web-api/overview/advanced/httpclient-message-handlers authoredcontent

HttpClient Message Handlers in ASP.NET Web API

by Mike Wasson

A message handler is a class that receives an HTTP request and returns an HTTP response.

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.

On the client side, the HttpClient class uses a message handler to process requests. The default handler is HttpClientHandler, which sends the request over the network and gets the response from the server. You can insert custom message handlers into the client pipeline:

[!NOTE] ASP.NET Web API also uses message handlers on the server side. For more information, see HTTP Message Handlers.

Custom Message Handlers

To write a custom message handler, derive from System.Net.Http.DelegatingHandler and override the SendAsync method. Here is the method signature:

[!code-csharpMain]

The method takes an HttpRequestMessage as input and asynchronously returns an HttpResponseMessage. A typical implementation does the following:

  1. Process the request message.
  2. Call base.SendAsync to send the request to the inner handler.
  3. The inner handler returns a response message. (This step is asynchronous.)
  4. Process the response and return it to the caller.

The following example shows a message handler that adds a custom header to the outgoing request:

[!code-csharpMain]

The call to base.SendAsync is asynchronous. If the handler does any work after this call, use the await keyword to resume execution after the method completes. The following example shows a handler that logs error codes. The logging itself is not very interesting, but the example shows how to get at the response inside the handler.

[!code-csharpMain]

Adding Message Handlers to the Client Pipeline

To add custom handlers to HttpClient, use the HttpClientFactory.Create method:

[!code-csharpMain]

Message handlers are called in the order that you pass them into the Create method. Because handlers are nested, the response message travels in the other direction. That is, the last handler is the first to get the response message.