Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient / HttpRequestMessage accept header parameters cannot have spaces

I'm dealing with an API that requires me to set the header application/json;masked=false in order to unmask some information. When setting the header using

var request = new HttpRequestMessage()
request.Headers.Add("Accept", "application/json;masked=false");

it appears as though a space is being added between the ; and masked making the output header application/json; masked=false. Unfortunately this API I'm working with appears to be checking only against the literal application/json;masked=false without the space. I know the header works, because if I use it without the space in postman it works fine. If I use the one C# is generating in postman, it does not.

Is there any way to override this behavior?

Thanks

like image 208
Thomas F. Avatar asked Jul 19 '17 15:07

Thomas F.


2 Answers

Alright, so through some digging, we ended up finding this github issue for the problem: https://github.com/dotnet/corefx/issues/18449 where they have a workaround which uses reflection.

I adopted their workaround to what I'm doing like so:

        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();
            }
        }
like image 157
Thomas F. Avatar answered Sep 30 '22 14:09

Thomas F.


This problem still exists in .NET 5, but I solved it by using:

request.Headers.TryAddWithoutValidation("Accept", "application/json;masked=false");

No reflection needed when using this method.

like image 35
Lars Olav Kjølstad Avatar answered Sep 30 '22 14:09

Lars Olav Kjølstad