How to define a DelegatingHandler for custom route?

343 Views Asked by At

I've created a DelegatingHandler and it works for every request. I've read some articles that i can define a handler for a specific route but I've tried a lot of ways without success, i'm missing something that i didn't found what is.

The last attempt was:

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    name: "SaveMessage",
    routeTemplate: "api/message/{type}",
    defaults: new { type = RouteParameter.Optional },
    constraints: null,
    handler: HttpClientFactory.CreatePipeline(
              new HttpControllerDispatcher(GlobalConfiguration.Configuration), 
              new DelegatingHandler[]{new ValidationHandler()})
);

My class Controller and method has the follow attributes:

[RoutePrefix("api/message")]
public class MessageController : ApiController
{
    [Route("{type}")]
    [HttpPost]
    public HttpResponseMessage Save(string type, [FromBody] Message message)
    {
        ....
    }
}

What is missing to my handler only works on requests like api/message/text?

I've read links like How to make more MapHttpRoutes for MVC 4 Api and http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection.

1

There are 1 best solutions below

3
On

The issue is the constraints that is set to null. You should define it like this for making it work for POST or GET:

constraints: new { httpMethod = new System.Web.Http.Routing.HttpMethodConstraint(HttpMethod.Post) }