我怎样才能得到 HttpHeaders.TryGetValues() 到 return 几个值?

How can I get HttpHeaders.TryGetValues() to return several values?

我正在使用 HttpHeaders.TryGetValues,但我不知道如何制作 return 几个 值。

这是我正在尝试的:

using System.Net.Http;

var response = await new HttpClient().GetAsync("https://httpbin.org/response-headers?X-Numbers=0,1,1,2,3,5,8");
var success = response.Headers.TryGetValues("X-Numbers", out var values);
Console.WriteLine($"{success} ({values.Count()}) -> '{values.First()}'");

结果如下:

True (1) -> '0,1,1,2,3,5,8'

像往常一样,文档真的很稀疏,关于 values 参数的所有内容都是

The specified header values.

RFC 2616 section 4.2 描述了 HTTP header 如何可以有多个值(强调我的):

Multiple message-header fields with the same field-name MAY be present in a message if and only if the entire field-value for that header field is defined as a comma-separated list [i.e., #(values)]. It MUST be possible to combine the multiple header fields into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field-value to the first, each separated by a comma. The order in which header fields with the same field-name are received is therefore significant to the interpretation of the combined field value, and thus a proxy MUST NOT change the order of these field values when a message is forwarded.

如我们所见,值是 comma-separated 所以我希望有 7 个值的可枚举 (0, 1, 1, 2358) 但 TryGetValues return 是单个字符串值。

我可以做些什么来让它 return 多个值吗?

source code 看来,Cache-Control header 的解析器有点独特:

The Cache-Control header is special: It is a header supporting a list of values, but we represent the list as one instance of CacheControlHeaderValue. I.e we set SupportsMultipleValues to true since it is OK to have multiple Cache-Control headers in a request/response message. However, after parsing all Cache-Control headers, only one instance of CacheControlHeaderValue is created (if all headers contain valid values, otherwise we may have multiple strings containing the invalid values).

要求 Cache-Control 总是 return 一个 String,据我所知,没有办法(缺少针对 donet/corefx 的 PR)欺骗它为你划分它。然而,other headers 会有不同的行为。

至于Cache-Control header为什么要这样特殊对待,你得问问真正的开发者了。自开源发布以来,该文件没有发生重大变化。

对于其他已知的 header,有一个大列表:KnownHeaders.cs。从那里您应该能够深入了解您感兴趣的任何特定 header。

TryGetValues returns 可枚举的原因是您可以提供多个具有相同名称的 headers,而且每个 header 可以有多个值,用逗号分隔,如你提到。即 "https://httpbin.org/response-headers?X-Numbers=0,1,1,2,3,5,8&X-Numbers=6".

我同意在 returned 值可枚举中将每个逗号分隔值作为单个值会更好,但当前实现假定每个 header 只能 return 一个值。