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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With