Content Headers Remove fails for string Authorization
The following test fails inexplicably:
[Test]
public void CrazyAssHttpRequestMessageTest()
{
var subject = new HttpRequestMessage()
{
Method = HttpMethod.Get,
Content = new StringContent("some content")
};
subject.Content.Headers.Remove("Authorization");
}
The exceptions is:
System.InvalidOperationException : Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
Why? Any other header seems to work fine, replace Authorization with something else and all is ok.
The HttpContentHeaders class only supports a subset of HTTP headers -- the headers relating to content. It seems a bit of an odd decision to split them up that way, but that's the way the framework works.
The upshot is that there will never be an Authorization header in request.Content.Headers
.
You get exactly the same error if you try to remove "Content-Type"
from HttpRequestHeaders or HttpResponseHeaders, or if you try to add an unexpected header to these collections without calling TryAddWithoutValidation. Even more frustrating is the fact that Contains()
will throw if you try to check for an invalid header. You can check for existence without throwing without worrying about the exact type of header collection using HttpHeaders.TryGetValues, or just use request.Content.Headers.Any(x => x.Key == "Authorization")
.
The classes linked above have a list of the headers they explicitly support (as strongly typed properties) eg HttpContentHeaders.ContentType.
链接地址: http://www.djcxy.com/p/46254.html上一篇: 无法在HttpFormUrlEncodedContent上设置标题
下一篇: 内容标题删除字符串授权失败