Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 5 so think I'm using System.Net.Http, Version=4.0.1.0

Here is the code I've tried:

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.

Can anyone help with this?

like image 632
dontbesorry80 Avatar asked Feb 17 '16 17:02

dontbesorry80


People also ask

How do I stop chunked transfer encoding?

Try adding "&headers=false" to your request. That should shorten it up and cause the response to be less likely to be chunked. Also, are you sending a HTTP/1.1 or HTTP/1.0 request? Try sending a HTTP/1.0 if your device cannot handle a HTTP/1.1 request.

What is the use of transfer encoding chunked?

Chunked transfer encoding allows a server to maintain an HTTP persistent connection for dynamically generated content. In this case, the HTTP Content-Length header cannot be used to delimit the content and the next HTTP request/response, as the content size is not yet known.


2 Answers

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.

like image 130
Kevin Smith Avatar answered Oct 19 '22 03:10

Kevin Smith


You can still use JsonContent in combination with LoadIntoBufferAsync, check out this answer. Example:

var content = JsonContent.Create(someObject);
await content.LoadIntoBufferAsync();
HttpResponseMessage response = await _httpClient.PutAsync($"/endpoint", content);
like image 42
Maksim Ramanovich Avatar answered Oct 19 '22 04:10

Maksim Ramanovich