Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST with transfer-enconding: chunked fails in IIS 8.5 web API

I have ASP.NET Web API running on IIS 8.5, and my POST method takes in a body of json document. Now a client app is using apache httpclient, which apparently automatically adds the Transfer-Encoding: chunked header into the request. My API method throws an exception because of non-existent body - it can't deserialize the json in the body, even though it looks good in the client logs.

How should I handle the request to ensure I get the whole body? I guess IIS should support transfer-encoding on the request as well, as it is part the HTTP/1.1 spec, right?

There's a similar question unanswered: Reading Body on chunked transfer encoded http requests in ASP.NET

like image 802
Tuomash Avatar asked Oct 30 '17 09:10

Tuomash


1 Answers

You have to basically check the ContentLength header and set it to null if it is 0.

public class ChunkJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        content.Headers.ContentLength = (content.Headers.ContentLength == 0) ? null : content.Headers.ContentLength;

        return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);
    }
}

Wire up this formatter

GlobalConfiguration.Configure(config =>
{
    var jsonFormatter = new ChunkJsonMediaTypeFormatter() { SerializerSettings = config.Formatters.JsonFormatter.SerializerSettings };
    config.Formatters.Remove(config.Formatters.JsonFormatter);
    config.Formatters.Insert(0, jsonFormatter);
}

https://gist.github.com/jayoungers/0b39b66c49bf974ba73d83943c4b218b

like image 60
Jerry Joseph Avatar answered Oct 03 '22 23:10

Jerry Joseph