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
How to add custom message handlers to the pipeline in Asp.Net webAPI C#?
To create a custom Server-Side HTTP Message Handler in ASP.NET Web API, we need to create a class that must be derived from the System.Net.Http.DelegatingHandler. Message handlers allow you to intercept HTTP requests and responses, enabling cross-cutting concerns like logging, authentication, caching, or request modification.
How Message Handlers Work
Message handlers form a pipeline where each handler can process the request before passing it to the next handler, and process the response on its way back. This provides a powerful mechanism for implementing middleware-like functionality in Web API.
Creating a Student Controller
Step 1 − First, create a controller and its corresponding action methods −
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Models {
public class Student {
public int Id { get; set; }
public string Name { get; set; }
}
}
namespace DemoWebApplication.Controllers {
public class StudentController : ApiController {
List<Student> students = new List<Student> {
new Student {
Id = 1,
Name = "Mark"
},
new Student {
Id = 2,
Name = "John"
}
};
public IEnumerable<Student> Get() {
return students;
}
public Student Get(int id) {
var studentForId = students.FirstOrDefault(x => x.Id == id);
return studentForId;
}
}
}
Creating a Custom Message Handler
Step 2 − Create a custom message handler class that derives from DelegatingHandler −
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DemoWebApplication {
public class CustomMessageHandler : DelegatingHandler {
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken) {
var response = new HttpResponseMessage(HttpStatusCode.OK) {
Content = new StringContent("Result through custom message handler..")
};
var taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();
taskCompletionSource.SetResult(response);
return await taskCompletionSource.Task;
}
}
}
In this example, the CustomMessageHandler class derives from DelegatingHandler and overrides the SendAsync() method. When an HTTP request arrives, this handler executes and returns a custom HTTP message without processing the request further, effectively short-circuiting the pipeline.
Registering the Message Handler
Step 3 − Register the CustomMessageHandler in the Global.asax class −
using System.Web;
using System.Web.Http;
public class WebApiApplication : System.Web.HttpApplication {
protected void Application_Start() {
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.MessageHandlers.Add(new CustomMessageHandler());
}
}
Creating a Practical Logging Handler
Here's a more practical example that logs requests and allows the pipeline to continue −
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DemoWebApplication {
public class LoggingMessageHandler : DelegatingHandler {
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken) {
Console.WriteLine($"Request: {request.Method} {request.RequestUri}");
// Call the next handler in the pipeline
var response = await base.SendAsync(request, cancellationToken);
Console.WriteLine($"Response: {response.StatusCode}");
return response;
}
}
}
This logging handler demonstrates how to process both the incoming request and outgoing response while allowing the request to continue through the pipeline by calling base.SendAsync().
Key Benefits of Message Handlers
-
Cross-cutting concerns − Handle logging, authentication, and caching across all API endpoints
-
Request/Response modification − Transform data before it reaches controllers or after it leaves them
-
Pipeline control − Short-circuit requests or implement conditional processing
-
Centralized logic − Implement common functionality once rather than in each controller
Output
When you run the application and navigate to your API endpoint, you will see the custom message from the handler instead of the actual controller response −
Result through custom message handler..
This demonstrates that the HTTP request never reaches the Get() action method because the custom message handler intercepts and responds to it directly.
Conclusion
Custom message handlers in ASP.NET Web API provide a powerful way to implement cross-cutting concerns and intercept HTTP requests/responses. By deriving from DelegatingHandler and overriding SendAsync(), you can create reusable components that handle logging, authentication, caching, and other middleware-like functionality across your entire API.
