4

I'm trying to add a route to my WebAPI with a custom message handler like so

config.Routes.MapHttpRoute(
    name: "TestRoute",
    routeTemplate: "Protected/TestMe",
    defaults: null,
    constraints: null,
    handler: new CustomHandler()
);

Handler code

internal class CustomHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage respMsg = new HttpResponseMessage();
        respMsg.Headers.Add("MyCustomHeader", "Test");
        respMsg.StatusCode = HttpStatusCode.NoContent;
        return Task.FromResult(respMsg);
    }
}

but everytime I access said route I am not getting my custom header back or teh NoContent code instead I'm receiving the result from route, but if I add the handler as a global one as this

config.MessageHandlers.Add(new CustomHandler());

it works and returns my custom header and the NoContent status code What am I missing in the route setup?

MabuaDev
  • 103
  • 1
  • 8
  • Hi, I know, it's not an answer but might help you: I just created new Web API application, added `Routes.MapHttpRoute` code to `WebApiConfig.Register` method, added `CustomHandler` right after `WebApiConfig` class and it just works for me as expected – Uriil Apr 04 '16 at 08:59
  • 1
    I believe the order in which MapHttpRoute calls are made are significant... have you played around with different placements in relation to whatever other handlers you might have? – jleach Apr 04 '16 at 09:02
  • 1
    Ty jdl it would seem my problem was I had config.MapHttpAttributeRoutes(); before my config.Routes.MapHttpRoute it seems to working now that I've reorder them. – MabuaDev Apr 04 '16 at 09:24

0 Answers0