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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With