Andrus
Andrus

Reputation: 27919

How to receive dynamic data in WebAPI controller

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?

Upvotes: 2

Views: 2267

Answers (1)

plog17
plog17

Reputation: 832

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
)

Upvotes: 3

Related Questions