如何使用HttpClient禁用ASP.Net C#中的分块传输编码 [英] How to disable Chunked Transfer Encoding in ASP.Net C# using HttpClient

查看:107
本文介绍了如何使用HttpClient禁用ASP.Net C#中的分块传输编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些JSON发布到外部API,由于我的内容被分块,因此该API一直失败。请有人告诉我如何禁用它吗?

I'm trying to post some JSON to an external API which keeps failing because my content is chunked. Please can someone tell me how to disable it?

我正在使用ASP.NET 5,所以我认为我正在使用System.Net.Http,Version = 4.0.1.0

I'm using ASP.NET 5 so think I'm using System.Net.Http, Version=4.0.1.0

这是我尝试过的代码:

using (var client = new HttpClient())
{
    // TODO - Send HTTP requests
    client.BaseAddress = new Uri(apiBaseUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("SAML", samlToken);
    client.DefaultRequestHeaders.TransferEncodingChunked = false;

    HttpResponseMessage response = await client.PostAsJsonAsync(path, jsonObject);
}

但是,似乎在将传输编码设置为分块时我检查了提琴手。

But It still seems to have the Transfer-Encoding set to "chunked" when I check Fiddler.

有人可以帮忙吗?

推荐答案

看来您也需要设置 Content-Length 标头,如果您不这样做,则似乎要使用 MaxRequestContentBufferSize HttpClientHandler 上在发送数据时对数据进行分块。

It looks like you need to set the Content-Length header too, if you don't it seems to use the MaxRequestContentBufferSize on HttpClientHandler to chunk the data when sending it.

尝试使用 StringContent ByteArrayContent StreamContent (如果可以找寻蒸汽),因为它们将能够计算

Try using a StringContent, ByteArrayContent or StreamContent (If the steam is seekable) as these will be able to calculate the length for you.

var content = new StringContent(json);

HttpResponseMessage response = await client.PostAsync(content);

PostAsJsonAsync 扩展方法创建 ObjectContent 不会计算 Content-Length 并返回false:

The PostAsJsonAsync extension methods create ObjectContent under the hood which doesn't calculate the Content-Length and return false:

public class ObjectContent : HttpContent
{
    /* snip */

    protected override bool TryComputeLength(out long length)
    {
        length = -1L;
        return false;
    }
}

因此,总会回到分块到缓冲区大小

Thus will always fall back to chunking to the buffer size.

这篇关于如何使用HttpClient禁用ASP.Net C#中的分块传输编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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