Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are built-in message handlers in Asp.Net webAPI C#?
A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class and provide us the opportunity to process, edit, or decline an incoming request before it reaches the HttpControllerDispatcher.
Message handlers are executed much earlier in the request processing pipeline, making them ideal for implementing cross-cutting concerns in Web API. They form a chain of classes that process HTTP requests and responses through a pipeline.
ASP.NET Web API Framework provides two types of message handlers −
- Server-Side HTTP Message Handlers
- Client-Side HTTP Message Handlers
Server-Side Message Handlers
On the server side, the Web API pipeline uses built-in message handlers that process requests in a specific order −
- HttpServer − Gets the request from the host and starts the pipeline processing.
- HttpRoutingDispatcher − Dispatches the request based on the configured route.
- HttpControllerDispatcher − Sends the request to the appropriate Web API controller.
Custom Server-Side Handlers
You can add custom handlers to the pipeline for cross-cutting concerns that operate at the HTTP message level. A custom message handler might −
- Read or modify request headers for authentication or logging
- Add response headers for CORS or caching policies
- Validate requests before they reach the controller
- Implement rate limiting or request throttling
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class CustomMessageHandler : DelegatingHandler {
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken) {
// Process the request before sending to next handler
request.Headers.Add("X-Custom-Header", "ProcessedByCustomHandler");
// Call the next handler in the pipeline
var response = await base.SendAsync(request, cancellationToken);
// Process the response before returning
response.Headers.Add("X-Response-Time", System.DateTime.UtcNow.ToString());
return response;
}
}
Client-Side HTTP Message Handlers
On the client side, the HttpClient class uses message handlers to process requests. The default handler is HttpClientHandler, which sends the request over the network and gets the response from the server.
Custom Client-Side Handler Example
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class LoggingHandler : DelegatingHandler {
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken) {
Console.WriteLine($"Sending request: {request.Method} {request.RequestUri}");
var response = await base.SendAsync(request, cancellationToken);
Console.WriteLine($"Received response: {response.StatusCode}");
return response;
}
}
public class Program {
public static async Task Main(string[] args) {
var handler = new LoggingHandler() {
InnerHandler = new HttpClientHandler()
};
using (var client = new HttpClient(handler)) {
var response = await client.GetAsync("https://api.example.com/data");
Console.WriteLine("Request completed");
}
}
}
The output of the above code is −
Sending request: GET https://api.example.com/data Received response: OK Request completed
Registering Message Handlers
To register a custom message handler in Web API, add it to the configuration during startup −
public static void Register(HttpConfiguration config) {
config.MessageHandlers.Add(new CustomMessageHandler());
// Other configuration...
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Comparison: Message Handlers vs Action Filters
| Message Handlers | Action Filters |
|---|---|
| Execute early in the pipeline, before routing | Execute closer to the controller action |
| Work with HTTP messages (request/response) | Work with controller context and action results |
| Good for cross-cutting concerns like logging, auth | Good for action-specific concerns like validation |
| Process all requests that match the handler | Process only requests to specific controllers/actions |
Conclusion
Message handlers in ASP.NET Web API provide a powerful mechanism to intercept and process HTTP requests and responses early in the pipeline. They are ideal for implementing cross-cutting concerns like authentication, logging, and request modification that apply across multiple controllers and actions.
