It is possible to add a MessageHandler only for a specific controller that is using Route Attributes?
I want to cut the request earlier in the pipeline if it doesn't contain certain headers. I want to mention that:
I can't add another route in WebApiConfig, we must use the Routing Attributes from the controller.
I don't want to add the MessageHandler globally.
It has to be a MessageHandler (early in the pipeline). We have alternatives for this but we are trying to do this more efficient.
For example, I've decorated the controller with the following RoutePrefix: api/myapicontroller and one action with Route(""). (I know it is strange, we are selecting a different action based on querystring)
Then, I've added
config.Routes.MapHttpRoute(
name: "CustomRoute",
routeTemplate: "api/myapicontroller/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: new myMessageHandler()
);
If I put this code before config.MapHttpAttributeRoutes();
the myMessageHandler is executing but I get this Message:
No action was found on the controller 'myapicontroller' that matches the request
If I put config.MapHttpAttributeRoutes();
first, the myMessageHandler is never executed but the my action inside myapicontroller is called.
Unfortunately, you can not set any handlers via AttributeRouting
. If you want to assign handler to specific routes you have to register it via MapHttpRoute
only. Except you need to add your controller name in defaults
section like in Ajay Aradhya's answer and remove Route
attribute from your action, because you are allowed to register routes either with Route
attribute or MapHttpRoute
method, but not both at the same time.
Also note that you need to create pipeline, otherwise you handler will work but request will not hit the controller action. See my answer on similar question for details.
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