当使用HttpClient.PostAsync(uri,TParam,MediaFormatter)时,传输编码被分块并且RequestBody被编码

时间:2018-09-10 06:51:26

标签: asp.net asp.net-mvc dotnet-httpclient

我正在尝试使用HttpClient.PostAsync调用API,并且收到错误请求。我检查了Fiddler,发现正文请求正在编码,并且Transfer-Encoding:在标题中分块。

response = Client.PostAsync(url, toSend, mediaTypeFormatter).Result;

toSend是一类

[DataContract]
public class OAuthRequestBody
{
    [DataMember(Name = "grant_type")]
    public string GrantType { get; set; }
    [DataMember(Name = "tpl")]
    public string Tpl { get; set; }
    [DataMember(Name = "user_login_id")]
    public string UserLogin { get; set; }
}

在这种情况下,Mediaformatter是Json,但可以有所不同,这就是为什么我们不使用JsonFormatter

当我在Fiddler中检查textView时,会看到以下内容:

 66
{"grant_type":"client_credentials","tpl":"{number}","user_login_id":"x"}
0

我不知道66和0的来源。

The Raw Headers:
POST http://example.com/token
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Accept: application/json
Accept-Encoding: gzip, deflate
Authorization: Basic FancyLongBase64
Host: example.com

66
{"grant_type":"client_credentials","tpl":"{number}","user_login_id":"x"}
0

我尝试了多种方法,但是编码似乎始终存在。也许有一些配置。

构建请求:

var body = new OAuthRequestBody
                {
                    GrantType = "client_credentials",
                    Tpl = Tpl,
                    UserLogin = "1"
                };

mediaTypeFormatter = new JsonMediaTypeFormatter();

url = "/token" //Not the actual path but same idea

0 个答案:

没有答案