8

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.

  • [this article](https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers) does the same but using `MapHttpRoute`. But that doesn't hold to `Attribute Routing` btw. – Nameless Mar 14 '17 at 11:28

2 Answers2

2

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.

RollerKostr
  • 331
  • 3
  • 7
-1

This article from MS docs explains the same. At last they provide a way to have controller specific handlers.But thats for the conventional routing. I don't know if this helps you or not.

config.Routes.MapHttpRoute(
    name: "MyCustomHandlerRoute",
    routeTemplate: "api/MyController/{id}",
    defaults: new { controller = "MyController", id = RouteParameter.Optional },
    constraints: null,
    handler: HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), new MyCustomDelegatingMessageHandlerA());
);
Nameless
  • 1,026
  • 15
  • 28