为什么我检查它们时 cache-control header 值倒退?

Why is cache-control header value backwards when I check against them?

headers 是这样附加的。

context.Response.Headers.Append("Cache-Control", "max-age=0,no-cache,no-store");

当我为一个单元测试做等式检查(如下)时,它失败了,因为当我读回它时,这 3 个项目的顺序是相反的("no-store,no-cache,max-age=0")。

Assert.IsTrue(resp.Result.Headers.GetValues("Cache-Control")
    .First()
    .Equals("max-age=0,no-cache,no-store"));

知道为什么会这样吗?或者,一种更好的方法来比较我的单元测试?

classHttpResponseHeaders属性是NameValueCollectiondocumentation for NameValueCollection 表示:

This class can be used for headers, query strings and form data.

Each element is a key/value pair.

Collections of this type do not preserve the ordering of element, and no particular ordering is guaranteed when enumerating the collection.

因此,您不能依赖特定的顺序。

如果您真的想检查集合 header 值是否存在,您可以改为执行字符串 Contains 操作。

然而,有人可能会争辩说,您实际上是在用它对 .NET 框架(而不是您的代码)进行单元测试。换句话说,您可能首先要重新考虑编写这样的测试。