HttpClient/HttpRequestMessage 接受头参数不能有空格 [英] HttpClient / HttpRequestMessage accept header parameters cannot have spaces
问题描述
我正在处理一个 API,它要求我设置标头 application/json;masked=false
以取消屏蔽某些信息.使用
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");
看起来好像在 ;
和 masked
之间添加了一个空格,使得输出头 application/json;掩码=假
.不幸的是,我正在使用的这个 API 似乎只检查没有空格的文字 application/json;masked=false
.我知道标题有效,因为如果我在邮递员中没有空格的情况下使用它,它可以正常工作.如果我使用在邮递员中生成的 C#,则不会.
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?
谢谢
推荐答案
好吧,经过一番挖掘,我们最终找到了这个问题的github issue:https://github.com/dotnet/corefx/issues/18449 他们有一个使用反射的解决方法.
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();
}
}
这篇关于HttpClient/HttpRequestMessage 接受头参数不能有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!