8
votes

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.

1
Have you tried subject.Request.Headers.Remove("Authorization"); ?Haney♦
@DaveHaney yes, that works, I wanted also to remove from request.contentCalin

1 Answers

7
votes

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) e.g. HttpContentHeaders.ContentType.