Pindakaas
Pindakaas

Reputation: 4439

how to post json request

I am trying to post a json request to my web api:

json:

[{
    'rows': [
        {
            'country': 'UK',
            'description': 'this is a desc',
            'gezien': true,
            'Count': 3,
            'url': 'een/twee',
            'stam': 'blabla',
            'kanaal': 'NOS'
        },
        {
            'url': 'drie/vier',
            'stam': 'divers',
            'kanaal': 'SRV'
        }

    ],
    'skip': 0,
    'take': 10,
    'total': 100
}]

my api controller looks like this:

 public class DataController : ApiController
    {
        // GET api/data
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/data/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/data
        public void Post([FromBody]string value)
        {
        }

        // PUT api/data/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/data/5
        public void Delete(int id)
        {
        }
    }

I am trying to hit the post method but the string value is null? I am using fiddler to post the request.

Upvotes: 0

Views: 102

Answers (1)

Anthony Chu
Anthony Chu

Reputation: 37520

You're posting a JSON array but the method is expecting a string. The model binder doesn't know how to deal with this, so you're getting a null.

There are a couple of ways to get around this...

One is to pass a JavaScript string by wrapping your JSON in quotes (and escape quotes inside the string where necessary). The method will now receive a string and the model binder will be able to bind it to your string parameter.

The second option, if you're using Web API 2 where the model binder is using Json.NET, is you can change your parameter to be of type JObject and pass in your original JSON. Json.NET will parse the JSON and put it into a JObject. You can work with this JObject or turn it back into JSON by calling .ToString() on it.

The third option would be to create a class to represent your input and change the parameter to a strongly typed object.

Upvotes: 1

Related Questions