Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 476
Calin Avatar asked Jun 27 '14 17:06

Calin


1 Answers

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.

like image 114
Bennor McCarthy Avatar answered Sep 19 '22 05:09

Bennor McCarthy