HTTP Message Handlers in ASP.NET Web API
Delegating handler introduction
A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.
So it look something like this :
For what purposes we can use it
We can use it for various purposes:
- Caching
- Logging
- Error Handling
- Custom Headers
- Throttling and Rate Limiting
- Compression/Decompression
- Authentication and Authorization
- Request/Response Transformation
How to use it in ASP .NET Web API
It is quite simple to use it , these are the steps:
1/ Create your handler class and inherit it from DelegatingHandler which comes from System.Net.Http.DelegatingHandler
2/ Override its SendAsync method, and implement your logic.
3/ Register your handler in services.
Letβs see it via code :
public sealed class LoggingHandler : DelegatingHandler
{
private readonly ILogger<LoggingHandler> _logger;
public LoggingHandler(ILogger<LoggingHandler> logger)
{
_logger = logger;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
_logger.LogInformation("Request: {Method} {RequestUri}", request.Method, request.RequestUri);
var response = await base.SendAsync(request, cancellationToken);
_logger.LogInformation("Response: {StatusCode}", response.StatusCode);
return response;
}
}
I am using delegating handler with Refit API so its registration looks like this :
// Registering the LoggingHandler as a scoped service
builder.Services.AddScoped<LoggingHandler>();
// TODO: The best approach is to read the base address from appsettings.json
builder.Services.AddRefitClient<IDogsAPI>()
.ConfigureHttpClient(client => client.BaseAddress = new Uri("some-api"))
.AddHttpMessageHandler<LoggingHandler>();
// Registering the DogsService as a scoped service
builder.Services.AddScoped<IDogsService, DogsService>();
You can register custom HttpClient like this if you are not using Refit
services.AddTransient<CustomHandler>();
services.AddHttpClient("some-client", c =>
{
c.BaseAddress = new Uri("some-address");
})
.AddHttpMessageHandler<CustomHandler>();
How is delegating handler different than middleware
Both middleware and delegating handler serve same purpose, they can can intercept the request and response.
Both can do short circuit and we can chain multiple delegate handler similar to middlewares.
In my opinion it is choosing right thing for right action, if you have to play with HttpClient and do some updates with request/response then delegate handlers are best choice.
GitHub Demo Code
Get demo code of this newsletter issue at my GitHub Repo
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place