ASP.NET Web Api - the structure does not convert JSON to an object when using Chunked Transfer Encoding

I have an http client in Android that sends HTTP PUT requests to a REST api implemented with C # and ASP.NET Framework WebApi.

The structure should be able to magically convert (deserialize) JSON into a model class (simple object) if the JSON fields match the properties of the C # class.

The problem occurs when HTTP requests come from Chunked Transfer Encoding, which makes Content-Length = 0 (according to http://en.wikipedia.org/wiki/Chunked_transfer_encoding ) and the structure cannot match the JSON that is in the Http request message, therefore 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 the entries are null when the client sends an http request.

As I understand it, the Chunked Transfer encoding is just a transfer property that the client or http server does not have to worry about the application layer (business transport layer). But it seems that the structure is not coping with this as we would like.

I could manually extract the JSON from HttpRequestMessage and de-serialize it to a MyData object, but I could not use the ASP.NET infrastructure mask. And you know the rule: the more code you add, the more errors you enter.

Is there a way to handle Http Put queries using the JSON, which come in the form of a packet encoded in ASP.NET Web Api 2?

EDIT . This is the model class for this example, which the infrastructure should instantiate when JSON is de-serialized

 public class MyData { public string NamePerson {get; set;} public int Age {get; set;} public string Color {get; set;} } 
+6
source share
1 answer

I recently came across the same problem 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.

+5
source

Source: https://habr.com/ru/post/976037/


All Articles