Search code examples
c#http-headersdotnet-httpclient

Appending headers won't work, while adding does


The usual HttpClient class has a property HttpRequestHeaders of type HttpRequestHeaderCollection. The regular usage of headers looks like this.

httpClient.HttpRequestHeaders.Add("x-tra", "nice");

Of course, we need to check if such a header already exists. Otherwise, there's a risk of collision leading to an exception. I noticed that the aforementioned class, also has a method Append() and as far I understand, it's used for adding items to the collection without the risk of collision.

But no... This didn't give me any such header in the colletion.

client.DefaultRequestHeaders.Append(new("x-tra", ["nice", "cozy"]));

This gave me the first one but no appended ones.

client.DefaultRequestHeaders.Add("x-tra", "nice");
client.DefaultRequestHeaders.Append(new("x-tra", ["cool", "cozy"]));

What am I doing wrong? Is there any use for that method at all in the context of headers or is it something that comes with the concept of collections? All the blogs on usage of HTTP clients mention adding and none of those I've seen mentions appending.


Solution

  • That HttpHeaders class has an Add method - notice the link to the correct class documentation - which adds to the headers collection.

    The Append method is the one from LINQ, where the newly added item is only present in the returned collection and not in the target DefaultRequestHeaders.

    From the Append documentation:

    This method does not modify the elements of the collection. Instead, it creates a copy of the collection with the new element.