How to receive dynamic data in Web API controller Post method

余生长醉 提交于 2019-11-28 02:07:31
plog17

If the structure of the JSON does not change

Having this will permit you to send the body like the one you provided at a url like API/Entity/someid?culture=en&layout=1.

To specify optional query parameter in your controller route, give them a default value like:

public class EntityController : APIController
{
    public HttpResponseMessage Post([FromUri]string culture="EN", [FromUri]int layout=1, YourBody body )
    { ... }
}

If YourBody is always like the one you mentionned, something like this should be deserialized automatically:

public class YourBody
{
    public Dictionary<string, string> HeaderData {get; set;}
    public Dictionary<string, string> RowData{get; set;}
}

and would give you full access to any element of the body.

If the structure of the JSON can change

Something like this would permit the receive any kind of json:

public HttpResponseMessage  Post([FromBody]JToken body)
{
    // Process the body
    return ...
}

You will need some extra validation since no object deserialization will be made. The only think you'll know is that your body is a JSON.

You therefore may want to parse it to see if it looks like what you are expecting. See that post about how to access element of a JSON with JToken.

For instance, you could do something like the following to handle a changing body content and still handle optional query parameters of your route :

public HttpResponseMessagePost([FromBody]JToken body, [FromUri]string culture="EN", [FromUri]int layout=1)
{
    JObject headerData= body["headerData"].Value<JObject>();
    JObject headerData= body["rowData"].Value<JObject>();
    return ...;
}

You may also read this about other alternatives for posting raw data to a webapi controller.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!