简体   繁体   中英

C# Web service, how to receive JSON

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

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

Looks like you already got a response, but here's the code for a working solution:

Note: I used JsonResult Actions in MVC3, but the principles are the same

Controller:

    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost] // requires HttpPost attribute
        public JsonResult SendData(SearchObject payload)
        {
            // do something here

            return Json(new { status = "Success" });
        }
    }

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

View:

@{
    ViewBag.Title = "Index";
}
<script src="../../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $.ajaxSetup({ accepts: "application/json" });
    $.ajax({
        url: '@Url.Action("SendData")', type: "POST",
        success: function (data) {
            alert(data.status); 
        },
        error: function (a, b, c) { },
        data: { 'Name':'Glenn','Type':'4','Meals':["1","2"] }
    });
</script>

<h2>Index</h2>

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM