C# Web service, how to receive JSON

asp.net-mvc, c#, javascript, json, web-services

Solution

You should use POST attribute with the method, this way you will be able to post complex object to the Web API,

You may create a class for the JSON, from json to cSharp

public class SearchObject
{
    public string Name { get; set; }
    public string Type { get; set; }
    public List<string> Meals { get; set; }
    public List<string> Excludes { get; set; }
}

Then in your web api, specify the method with HttpPost attribute, Web API will take care of deserialization of json in the post to your template.

[HttpPost]
public string Search(SearchObject json)
{
    return "Asdasd";
}

You may try fiddler, for making a post request, in the request header specify type:

Content-Type:application/json

and in the request body paste your json, and Execute

Problem

I made a JSON string with jquery, and i want to send it to a C# web api controller. This is an example of the JSON object ``` {"Name":"","Type":"4","Meals":["2","3"],"Excludes":["Beef","Chicken"]} ``` I tryed to send it with a URL like this ``` API/Recipe/Search?json={"Name":"","Type":"4","Meals":["2","3"],"Excludes":["Beef","Chicken"]} ``` With my Controller like this: ``` public class RecipeController : ApiController { [HttpGet] public string Search(searchObject json) { return "Asdasd"; } } ``` and like this ``` public class RecipeController : ApiController { [HttpGet] public string Search(string json) { searchObject search = (searchObject)JsonConvert.DeserializeObject(json); return "Asdasd"; } } ``` But in neither case the controller will pick it up. I am using MVC4. Here is the Jquery i am using to make the call. apiLink is the link I posted above. ``` $.getJSON(apiLink, function (data) { var items = []; $.each(data, function (key, val) { items.push('<li id="' + key + '">' + val + '</li>'); }); $('<ul/>', { 'class': 'my-new-list', html: items.join('') }).appendTo('body'); }); ``` How do I get the controller to receive the JSON object? Thanks

Original source