HttpClient / HttpRequestMessage accept header parameters cannot have spaces

↘锁芯ラ 提交于 2019-12-10 17:07:58

问题


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


回答1:


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();
            }
        }


来源:https://stackoverflow.com/questions/45194549/httpclient-httprequestmessage-accept-header-parameters-cannot-have-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!