HttpClient / HttpRequestMessage接受标头参数不能有空格 [英] HttpClient / HttpRequestMessage accept header parameters cannot have spaces

查看:350
本文介绍了HttpClient / HttpRequestMessage接受标头参数不能有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个API,该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");

它似乎在之间添加了空格; 屏蔽了,使输出标头 application / json; masked = false 。不幸的是,我正在使用的该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问题: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆