Loading

ASP.NET Web API

How to implement HTTP Client Message Handler in Web API with Real-Time?. The Complete ASP.NET Web API Developer Course 2022 [Videos].

In this Video, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we alwatchy 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 alwatchy discussed
  2. Client Side HTTP Message Handlers – will discuss in this Video
HTTP Client Message Handlers in Web API

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.Thwatching.Tasks;
namespace ClientSideMessageHandler.Models
{
class MessageHandler1 : DelegatingHandler
{
private int _count = 0;
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, System.Thwatching.CancellationToken cancellationToken)
{
System.Thwatching.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.Thwatching.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.Thwatching.CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (!response.IsSuccessStatusCode)
{
_writer.WriteLine("{0} {1} {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 Video, I am going to discuss How to Implement the Token Based Authentication in ASP.NET Web APIHere, in this Video, I try to explain HTTP Client Message Handler in Web API with some examples. I hope this Video will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this Video.

See All

Comments (561 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET Web API / Blog

What is ASP.NET Web API Application?

In this ASP.NET Web API Tutorials series, I covered all the features of ASP.NET Web API. You will learn from basic to advance level features of ASP.NET Web API. The term API stands for “Application Programming Interface” and ASP.NET Web API is a framework provided by Microsoft which makes it easy to build Web APIs, i.e. it is used to develop HTTP-based web services on the top of .NET Framework.
3-Feb-2022 /34 /561

ASP.NET Web API / Blog

How to creat ASP.NET Web API Application using Visual Studio?

In this article, I am going to discuss the step-by-step procedure for Creating ASP.NET Web API Application. Please read our previous article before proceeding to this article where we gave an overview of the ASP.NET Web API framework. As part of this article, we ate going to discuss the following pointers.
3-Feb-2022 /34 /561

ASP.NET Web API / Blog

How to add Swagger in Web API Application?

In this article, I am going to discuss how to add Swagger in Web API Application to document and test restful Web API services. Please read our previous article where we discussed How to Create an ASP.NET Web API Application step by step before proceeding to this article as we are going to work with the same example. As part of this article, we are going to discuss the following pointers.
3-Feb-2022 /34 /561