HTTP Client Message Handler

HTTP Client Message Handler with Real-Time examples

In this article, I am going to discuss HTTP Client Message Handler with real-time examples. As we already discussed in HTTP Message Handler Article that a Message Handler is a class that receives an HTTP request and returns an HTTP response. The Message handler is derived from the abstract HttpMessageHandler class. There are two types of HTTP Message Handlers as follows

  1. The Server Side HTTP Message Handlers – we already discussed
  2. Client Side HTTP Message Handlers – will discuss in this article
HTTP Client Message Handlers

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. As a developer if you want, then you can also create your own custom message handlers and then insert the custom message handlers into the pipeline in the client side as shown in the below image.

HTTP Client Message Handler

Creating a Custom HTTP Client Message Handler:

Let us discuss how to create a Custom HTTP Client Message Handler. To create a custom HTTP Client message handler, what we need to do is, we need to create a custom class and that class should be derived from the System.Net.Http.DelegatingHandler class. Then the class should override the SendAsync method. The signature of the SendAsync method as following:

HTTP Client Message Handler

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

  1. Process the request message.
  2. Call the base.SendAsync method to send the request to the inner handler.
  3. The inner handler returns a response message. (This step is asynchronous.)
  4. Process the response message and returns the response to the caller.
Creating a Custom Message Handler:

The following example shows the creation of a custom message handler which adds a custom header to the outgoing request:

using System.Net.Http;
using System.Threading.Tasks;

namespace ClientSideMessageHandler.Models
{
    class MessageHandler1 : DelegatingHandler
    {
        private int _count = 0;
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            System.Threading.Interlocked.Increment(ref _count);
            request.Headers.Add("X-Custom-Header", _count.ToString());
            return base.SendAsync(request, cancellationToken);
        }
    }
}

The call to the base.SendAsync method is asynchronous. If your handler going to do some work after this call, then use the await keyword to resume execution after the method completes.

The following example shows a handler that logs error codes. The example shows how to get at the response inside the handler.

using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace ClientSideMessageHandler.Models
{
    class LoggingHandler : DelegatingHandler
    {
        StreamWriter _writer;

        public LoggingHandler(Stream stream)
        {
            _writer = new StreamWriter(stream);
        }

        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                _writer.WriteLine("{0}\t{1}\t{2}", request.RequestUri,
                    (int)response.StatusCode, response.Headers.Date);
            }
            return response;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _writer.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
Adding Message Handlers to the Client Pipeline

To add a custom message handlers to HttpClient pipeline, we need to use the HttpClientFactory.Create method as shown below.

HttpClient client = HttpClientFactory.Create(new MessageHandler1(), new MessageHandler2());

The Message handlers are called in the order that we pass them into the Create method of the HttpClientFactory class. The reason is handlers are nested the response message travels in the other direction. That is, the last handler is the first to get the response message.

In the next article, I will discuss How to Implement the Token Based Authentication in ASP.NET Web API.

SUMMARY

In this article, I try to explain HTTP Client Message Handler with some examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “HTTP Client Message Handler”

  1. Pingback: My Homepage

Leave a Reply

Your email address will not be published. Required fields are marked *