HttpResponseMessage.Content.Headers ContentDisposition为null

时间:2014-01-08 23:07:16

标签: c# dotnet-httpclient

使用HttpClient下载文件时,我首先下载标题然后下载内容。下载头文件时,我可以在HttpResponseMessage的Content属性上看到Headers集合,但是当通过Headers上的ContentDisposition访问它时,得到null screenshot

为什么会这样?提琴手显示标题很好......

代码:

var responseMessage = await httpClient.GetAsync(uri, 
HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(continueOnCapturedContext: false);

更新1

看起来这个类遵循RFC 2616中概述的Content-Disposition实现,并且无法处理Content-Disposition实现更新RFC 6266。 RFC 2616将filename参数值定义为引用字符串,其中更新RFC 6266仅表明它应该是

RFC 2616语法

content-disposition = "Content-Disposition" ":"
                          disposition-type *( ";" disposition-parm )
    disposition-type = "attachment" | disp-extension-token
    disposition-parm = filename-parm | disp-extension-parm
    filename-parm = "filename" "=" quoted-string
    disp-extension-token = token
    disp-extension-parm = token "=" ( token | quoted-string )

RFC 6266语法

content-disposition = "Content-Disposition" ":"
                        disposition-type *( ";" disposition-parm )

 disposition-type    = "inline" | "attachment" | disp-ext-type
                     ; case-insensitive
 disp-ext-type       = token

 disposition-parm    = filename-parm | disp-ext-parm

 filename-parm       = "filename" "=" value
                     | "filename*" "=" ext-value

 disp-ext-parm       = token "=" value
                     | ext-token "=" ext-value
 ext-token           = <the characters in token, followed by "*">

其中ext-value = <ext-value, defined in [RFC5987], Section 3.2>

实施例

工作案例

Working case

失败案例

Failing case

更新2

使用MS connect打开ticket

更新3

Microsoft已承认this is a bug并将解决此问题。

2 个答案:

答案 0 :(得分:4)

谢谢 - 发现这对我有帮助。为了他人的利益,这是我的解决方法(显然这是仍然今天的事情???)

我处于一个受控制的环境中,因此以下代码假定:

  • 只有一个Content-Disposition标头
  • 标记的格式为:inline; "filename";

这将重置响应的ContentDisposition标头,以便后续代码无缝工作:

<!-- language: c# -->
if (response.Content.Headers.ContentDisposition == null)
{
  IEnumerable<string> contentDisposition;
  if (response.Content.Headers.TryGetValues("Content-Disposition", out contentDisposition))
  {
   response.Content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(contentDisposition.ToArray()[0].TrimEnd(';').Replace("\"",""));
  }
}

答案 1 :(得分:2)

问题在于尾随;在content-disposition标题

        [Fact]
        public void ParseContentDispositionHeader()
        {
            var value = ContentDispositionHeaderValue.Parse("attachment; filename=GeoIP2-City_20140107.tar.gz");
            Assert.Equal("GeoIP2-City_20140107.tar.gz",value.FileName);
        }

如果我添加分号,则解析将失败。如果你看一下RFC6266语法,分号只应该在参数之前。