I have a custom message handler that I add globally as follows:
public class CustomerHandler : DelegatingHandler
{
public CustomHandler(HttpConfiguration httpConfiguration)
{
InnerHandler = new HttpControllerDispatcher(httpConfiguration);
}
}
config.MessageHandlers.Add(new CustomHandler(config));
However, I get the following error:
The 'DelegatingHandler' list is invalid because the property 'InnerHandler' of 'CustomHandler' is not null. Parametername: handlers
So I changed the code to:
config.MessageHandlers.Add(new CustomHandler(config) { InnerHandler = null });
And I get an error:
ArgumentNullException
When I add the handler to the individual routing, it works fine.
var customHandler = new CustomHandler(config);
config.Routes.MapHttpRoute(
name: "default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" },
handler: customHandler
);
So it always throws an exception when the Innerhandler
is set correctly or null.
What am I missing?
EDIT
This custom handler is used to check that a particular header is in the request and if found, gets the user details from a memory cache. Would it make more sense to change from a handler to a module?
First you should read up on HTTP Message Handlers in ASP.NET Web API to get a better understanding of the handlers.
Message handlers are called in the same order that they appear in MessageHandlers collection. Because they are nested, the response message travels in the other direction. That is, the last handler is the first to get the response message.
Notice that you don't need to set the inner handlers; the Web API framework automatically connects the message handlers.
If intending to add the handler to the pipeline then you should not set the inner handler. the framework will do that based on the order the delegating handler was added to the pipeline.
When adding the handler to the route directly there is no need for the inner handler so that is why it works as you stated in the OP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With