How to disable Chunked Transfer Encoding in ASP.Net C# using HttpClient

前端 未结 1 1550
名媛妹妹
名媛妹妹 2020-12-17 09:24

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?

I\'m using ASP.NET

相关标签:
1条回答
  • 2020-12-17 09:59

    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.

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

    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.

    0 讨论(0)
提交回复
热议问题