I haven API-Controller serving files via GET-Requests. I'm using the PushStreamContentResponse and that works well.
I can also set the Content-Length-Header on the response object.
Now I also want to support HEAD-Requests. I've tried http://www.strathweb.com/2013/03/adding-http-head-support-to-asp-net-web-api/ and while that may work, I need a solution where I don't need to actually process the request: Retrieving the file and streaming it is expensive, but getting the meta data (length, etc) is practically a no-op.
However, when I try to set the Content-Length header, it will be overwritten with 0.
I have added request tracing and I see that the message returned by my handler is displayed with the correct URL, Content-Disposition and Content-Length.
I have also tried using a custom HttpResponse and implement the TryComputeLength. And while this method is indeed called, the result is discarded at some point in the pipeline.
Is there any way to support this using Web API?
While this might have been an issue in 2015, today (2017 onwards), you can just do this
both
HEAD api/webhooks/survey-monkey
andPOST api/webhooks/survey-monkey
work just fine. (this is the stub I've just done for implementing SurveyMonkey's webhooks)Another solution would be to create a custom
HttpContent
that will does this job for you. Also a customisedIHttpActionResult
is needed if you want to stick to the guidelines.Let's say you have a controller that return a
HEAD
action for a given resource like that:The solution I came up with is as follow:
The head handler
The empty content
The buffering policy selector
The buffering policy should be set into the
public static void Register(HttpConfiguration config)
method called inApplication_Start()
, like that:Also, check if the server is configured to accept
HEAD
!This solution has few advantages:
HEAD
is handled through the WebAPI APII created a Web API 2 file store controller that supports
HEAD
through a similar mechanism.Thanks to Henning Krause for its question and answer that led me there.
In the end, it was really simple.
The WebAPI will, by default, disable output buffering for StreamContent and PushStreamContent. However, this behavior can be overridden by replacing the WebHostBufferPolicySelector via Application_Startup: