问题
I have an http client in Android sending HTTP PUT requests to a REST api implemented with C# and ASP.NET WebApi framework.
The framework should be able to magically convert (deserialize) the JSON into a model class (plain object) as long as the JSON fields match the properties in the C# class.
The problem comes when the http requests come with Chunked Transfer Encoding that makes the Content-Length = 0 (as per http://en.wikipedia.org/wiki/Chunked_transfer_encoding) and the framework is not able to map the JSON that's within the Http request message so the parameter is null.
See this simple example:
[HttpPut]
public HttpStatusCode SendData(int id, int count, [FromBody]MyData records, HttpRequestMessage requestMessage)
{
var content = requestMessage.Content;
string jsonContent = content.ReadAsStringAsync().Result; //this gets proper JSON
return HttpStatusCode.OK;
}
The problem is that records is null when the client sends the http request chunked.
As I understand, the Chunked Transfer encoding is simply a transfer property that the http client or server should not have to worry about at the application layer (transport layer's business). But it seems the framework doesn't manage it as I'd like.
I could manually retrieve the JSON from the HttpRequestMessage and de-serialize it into a MyData object, but I wouldn't be able to take advantage of the ASP.NET framework's magic. And you know the rule: the more code you add the more bugs you are likely to introduce.
Is there any way to handle Http Put requests with JSON that come as chunked transfer encoded in ASP.NET Web Api 2?
EDIT: This is the model class for this example that the framework should instantiate when de-serializing the JSON
public class MyData
{
public string NamePerson {get; set;}
public int Age {get; set;}
public string Color {get; set;}
}
回答1:
I recently stumbled upon the the same issue, and managed to create a workaround for it. I took the original JsonMediaTypeFormatter class, subclassed it and updated the implementation of the ReadFromStreamAsync/ReadFromStream-method.
https://gist.github.com/cobysy/578302d0f4f5b895f459
Hope this helps.
来源:https://stackoverflow.com/questions/26111850/asp-net-web-api-the-framework-is-not-converting-json-to-object-when-using-chun