user2617874
user2617874

Reputation: 101

Sending list of objects to Web API

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;
    }

Upvotes: 4

Views: 18871

Answers (2)

krescruz
krescruz

Reputation: 418

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";
}

Upvotes: 4

Tomasz Jaskuλa
Tomasz Jaskuλa

Reputation: 16033

I don't know really how your JSON is serialized in the line js.Serialize(str); I suspect that this line is the core problem. Sending JSON is better suited in the POST Request body than in the query string. Anyways, I think that HttpClient is better suited for working with WebApi because it offers symmetric programming experience. You could try something like that with HttpClient :

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(URI);

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("api_key", token);

    var content = new ObjectContent(syncString, new JsonMediaTypeFormatter());

    var result = client.PostAsync("/api/Food/", content).Result;
}

Upvotes: 2

Related Questions