Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add MessageHandler for a specific controller that is using Routing Attributes in ASP.NET WebAPI 2?

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.

like image 567
Florin-Constantin Ciubotariu Avatar asked Mar 09 '17 18:03

Florin-Constantin Ciubotariu


1 Answers

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.

like image 122
RollerKostr Avatar answered Oct 06 '22 14:10

RollerKostr