将对象列表发送到Web API

时间:2013-12-03 10:21:36

标签: c# asp.net-web-api

我无法将对象列表发送到webapi控制器。

这是控制器:

[AcceptVerbs("POST")]
public string syncFoodData(List<intakeSync> str)
{
    string apikey = Request.Headers.GetValues("api_key").ToArray()[0];
    return "data syncronised";
}

这是班级:

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

str的值始终为null。

这是将httprequest发送到webapi

的web方法
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;
    }

2 个答案:

答案 0 :(得分:4)

您可以使用:

在Json中请求正文

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

Api Rest .net C#

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

答案 1 :(得分:2)

我真的不知道您的JSON是如何在行js.Serialize(str);中序列化的。我怀疑这一行是核心问题。发送JSON比在查询字符串中更适合POST请求主体。无论如何,我认为HttpClient更适合使用WebApi,因为它提供了对称的编程体验。您可以使用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;
}