Skip to content

HttpClient: Impossible to send "Accept: a;charset=b" #21131

@zugzwangm

Description

@zugzwangm

I want to make a http request with a header "Accept" with value "a;charset=b".
It is impossible to do that with HttpClient.

using (var client = new HttpClient())
{
	client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "a;charset=b");
	// ...
}

This will generate a request with header "Accept" with value "a; charset=b".
Yes, this extra space is obviously valid, but the original value was also valid. And there are APIs out there that won't work with the extra space.

The only way to make it work is to hack it with reflection:

client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "foo");
foreach (var v in client.DefaultRequestHeaders.Accept)
{
	if (v.MediaType.Contains("foo"))
	{
		var field = v.GetType().GetTypeInfo().BaseType.GetField("_mediaType", BindingFlags.NonPublic | BindingFlags.Instance);
		field.SetValue(v, "a;charset=b"); // avoid MediaType's validation
		v.CharSet = "";					
	}
}

Sugestion:

client.DefaultRequestHeaders.AddHeaderAndDontMessWithItDontChangeItDontParseItIWantTotalControlThankYouVeryMuch("Whatever header I want", "Whatever value I want");

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Net.HttpenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions