Web API-处理HEAD请求并指定自定义Content-Length [英] Web API - Handling HEAD requests and specify custom Content-Length

查看:154
本文介绍了Web API-处理HEAD请求并指定自定义Content-Length的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有API控制器通过GET-Requests提供文件.我使用的是PushStreamContentResponse,效果很好.

I haven API-Controller serving files via GET-Requests. I'm using the PushStreamContentResponse and that works well.

我还可以在响应对象上设置Content-Length-Header.

I can also set the Content-Length-Header on the response object.

现在,我也想支持HEAD-Requests.我已经尝试过 http://www.strathweb.com/2013/03/adding-http-head-support-to-asp-net-web-api/,虽然这可能有效,但我需要不需要的解决方案实际处理请求:检索文件并对其进行流传输很昂贵,但是获取元数据(长度等)实际上是一项禁忌.

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.

但是,当我尝试设置Content-Length标头时,它将被0覆盖.

However, when I try to set the Content-Length header, it will be overwritten with 0.

我添加了请求跟踪,并且看到处理程序返回的消息显示了正确的URL,Content-Disposition和Content-Length.

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.

我也尝试过使用自定义HttpResponse并实现TryComputeLength.尽管确实调用了此方法,但结果会在管道中的某个点被丢弃.

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.

有什么方法可以使用Web API来支持它?

Is there any way to support this using Web API?

推荐答案

最后,它真的很简单.

  1. 为HEAD请求创建处理程序
  2. 返回至少包含一个字节内容的正文,将响应的Content-Length-Header设置为所需的长度.使用长度为零的Body无效.
  3. 这是关键部分:禁用响应的输出缓冲.

默认情况下,WebAPI将禁用StreamContent和PushStreamContent的输出缓冲.但是,可以通过Application_Startup替换WebHostBufferPolicySelector来覆盖此行为:

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:

GlobalConfiguration.Configuration.Services.Replace(typeof (IHostBufferPolicySelector), new BufferlessHostBufferPolicySelector());

这篇关于Web API-处理HEAD请求并指定自定义Content-Length的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆