Sending list of objects to Web API

asp.net-web-api, c#

Solution

You can use this :

Request body in Json

[{id:1, nombre:"kres"},
{id:2, nombre:"cruz"}]

Api Rest .net C#

public string myFunction(IEnumerable<EntitySomething> myObj)
{
    //...
    return "response";
}

Problem

I am having trouble sending a list of objects to a webapi controller. This is the controler: ``` [AcceptVerbs("POST")] public string syncFoodData(List<intakeSync> str) { string apikey = Request.Headers.GetValues("api_key").ToArray()[0]; return "data syncronised"; } ``` This is the class: ``` public class intakeSync { public int memberID { get; set; } public Double size { get; set; } public string food { get; set; } public string token { get; set; } public string time { get; set; } public string date { get; set; } public string nocatch { get; set; } public string calories { get; set; } } ``` The value of str is always null. this is the webmethod that sends the httprequest to the webapi ``` public static string syncIntakeData(string token, string[] syncString) { JavaScriptSerializer js = new JavaScriptSerializer(); List<intakeSync> str = new List<intakeSync>(); for (int i = 0; i <= syncString.Length - 1; i++) { str.Add(js.Deserialize<intakeSync>(syncString[i])); } string url = URI + "/api/Food/?str=" +js.Serialize(str); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.Headers.Add("api_key", token); Stream requestStream = request.GetRequestStream(); StreamReader read = new StreamReader(request.GetResponse().GetResponseStream()); string dat = read.ReadToEnd(); read.Close(); request.GetResponse().Close(); return dat; } ```

Original source