DelegatingHandlers not executing when routes not defined

Multi tool use


DelegatingHandlers not executing when routes not defined
I am working on a WebAPI 2 project which currently uses attribute-based routing exclusively, to the point that there are no routes defined in registration, and everything is working as expected.
However, I am now adding a DelegatingHandler
to provide a heartbeat that I can ping with a HEAD request:
DelegatingHandler
public class HeartbeatMessagingHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (IsHeartbeat(request))
{
if (request.Method == HttpMethod.Head)
{
var response = new HttpResponseMessage(HttpStatusCode.NoContent) { Content = new StringContent(string.Empty) };
var task = new TaskCompletionSource<HttpResponseMessage>();
task.SetResult(response);
return task.Task;
}
}
return base.SendAsync(request, cancellationToken);
}
private static bool IsHeartbeat(HttpRequestMessage request)
{
return request.RequestUri.LocalPath.Equals("/Heartbeat", StringComparison.OrdinalIgnoreCase);
}
}
However, the handler is not being invoked if I make the expected HEAD http://localhost/heartbeat
request; if I call any route that does exist then the handler is invoked; and if I add an old-school routing configuration then the handler is invoked on the expected /heartbeat
endpoint.
HEAD http://localhost/heartbeat
/heartbeat
So, using attribute routing only, how can I handle a request to a "virtual" endpoint?
1 Answer
1
Most likely your handler is too late in the pipeline and a higher pipeline is short-circuiting the request before your handler has time to execute.
consider inserting your handler higher up so it has a better chance of intercepting the request
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Web API routes
config.MapHttpAttributeRoutes();
// add to the front of the pipeline
config.MessageHandlers.Insert(0, new HeartbeatMessagingHandler());
}
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Have you tried adding the handler earlier in the handlers? Show WebApiConfig.
– Nkosi
25 mins ago