HttpClient / HttpRequestMessage accept header parameters cannot have spaces
I am dealing with an API that requires me to set a header application/json;masked=false
in order to expose some information. When setting the title with
var request = new HttpRequestMessage()
request.Headers.Add("Accept", "application/json;masked=false");
it seems like a space is added between ;
and masked
, creating an output header application/json; masked=false
. Unfortunately, this API I'm working with seems to only be checked against literal application/json;masked=false
no whitespace. I know the header works because if I use it with no space in the postman it works great. If I use one C # that is generated in postman it is not.
Can this behavior be overridden?
thank
source to share
Ok, so after some digging, we ended up looking for this github issue for the issue: https://github.com/dotnet/corefx/issues/18449 where they have a workaround that uses reflection.
I have applied a workaround to what I am doing like this:
request.Headers.Add("Accept", contentType);
foreach (var v in request.Headers.Accept)
{
if (v.MediaType.Contains("application/json"))
{
var field = v.GetType().GetTypeInfo().BaseType.GetField("_mediaType", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(v, "application/json;masked=false");
v.Parameters.Clear();
}
}
source to share