What you can do is use the per-route message handler but be careful here. As the article that @Nick linked in his answer, you can chain the handler and ensure that the HttpControllerDispatcher
is involved. Otherwise, you won't get into the Controller pipeline.
One other option which I like is to use the HttpControllerDispatcher
as a base class for your custom handler:
public class CustomerOrdersDispatcher : HttpControllerDispatcher {
public CustomerOrdersDispatcher(HttpConfiguration config)
: base(config) {
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken) {
// Do some stuff here...
return base.SendAsync(request, cancellationToken);
}
}
Here, how you will register it:
protected void Application_Start(object sender, EventArgs e) {
var config = GlobalConfiguration.Configuration;
config.Routes.MapHttpRoute(
name: "CustomerOrdersHttpRoute",
routeTemplate: "api/customers/{customerKey}/orders/{key}",
defaults: new { controller = "CustomerOrders", key = RouteParameter.Optional },
constraints: null,
handler: new CustomerOrdersDispatcher(config)
);
config.MessageHandlers.Add(new SomeOtherHandler1());
config.MessageHandlers.Add(new SomeOtherHandler2());
}
After SomeOtherHandler1
and SomeOtherHandler2
are executed, your CustomerOrdersDispatcher
will be executed for CustomerOrdersHttpRoute route. So, you can see that you preserve the default handler behavior and set some global handlers while you have a route specific one as well.
Here is the full implementation of my CustomerOrdersDispatcher
: https://github.com/tugberkugurlu/AdvancedWebAPI/blob/master/PerRouteMHOwnershipSample/Dispatcher/CustomerOrdersDispatcher.cs.
You may view the full sample application source code as well to see how it works out: https://github.com/tugberkugurlu/AdvancedWebAPI/tree/master/PerRouteMHOwnershipSample