How to receive dynamic data in WebAPI controller

2019-07-11 05:46发布

ASP.NET MVC4 WebAPI Post controller receives json data in POST buffer. Object contains two fixed name properties, headerData and rowData. They have have variable number of properties like

{"headerData": {
    "Tasudok": "134",
    "Kuupaev": "2015-11-23",
    "Dokumnr": "135319"
   },


"rowData": {
  "Toode":"",
  "Kogus":"0.0000",
  "Nimetus":"öäölä<a",
  "_rowsum":"0.00",
  "Id":"1639",
  "Dokumnr":"135319",
  "_oper":"edit",
  "_rowid":"1639"
  }
}

For example in some call rowData may contain additional properties and some rowData properties may be missing. Data is posted to ASP.NET MVC4 Web API using URL like API/Entity/someid?culture=en&layout=1 with default routing.

How to receive parameters in WebAPI controller ?

I tried according to How to receive dynamic data in Web API controller Post method

public class EntityController : APIController
{

    public class Body
    {   Dictionary<string, string> headerData { get; set; }
        Dictionary<string, string> rowData { get; set; }
    }

    public HttpResponseMessage Post(string id, Body body,
        [FromUri]string culture = null,
        [FromUri]uint layout = 0
        )
    { ... }
}

But body.headerData and body.rowData have are empty. How to get values into them?

1条回答
▲ chillily
2楼-- · 2019-07-11 06:45

Instead of

public class Body
{   
    Dictionary<string, string> headerData { get; set; }
    Dictionary<string, string> rowData { get; set; }
}

explicitly mark your class members as public so the deserializer can do its job !

The following should work:

public class Body
{   
    public Dictionary<string, string> headerData { get; set; }
    public Dictionary<string, string> rowData { get; set; }
}

And also, specify that id will come from the url:

public HttpResponseMessage Post(Body body,
    [FromUri]string id, 
    [FromUri]string culture = null,
    [FromUri]uint layout = 0
)
查看更多
登录 后发表回答