Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restrict a delegating handler to a specific route in Web API?

I have a custom delegating handler that manages the authentication of a request. In one of my controllers, authentication should not be enabled for a specific action. How can I disable the delegating handler for the method and route POST api/MyController?

One option is to hard code the route inside the handler, however, I would rather keep this logic out of the handler. In addition, I see myself adding this behavior to a few more actions, which can make this method hard to maintain.

protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
    if (request.Method == HttpMethod.Post
        && request.RequestUri.PathAndQuery.StartsWith("/api/MyController"))
        return base.SendAsync(request, cancellationToken);

    // Do authentication
}

Is there a better way that's easier to maintain?

like image 593
Omar Avatar asked Dec 29 '13 18:12

Omar


1 Answers

When mapping the routes, there is an overload of MappHttpRoute that allows you to specify a HttpMessageHandler. You can add your handler to all the routes that need it and omit it for the route that should not use it.
For more information see this link. The following sample is taken from this resource:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "Route1",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "Route2",
            routeTemplate: "api2/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: null,
            handler: new MessageHandler2()  // per-route message handler
        );

        config.MessageHandlers.Add(new MessageHandler1());  // global message handler
    }
}
like image 96
Markus Avatar answered Oct 22 '22 23:10

Markus