如何将带有字符串作为参数的列表项传递给mvc4中的web api

时间:2015-05-09 07:24:21

标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api

我创建了一个web api,其中我传递了两个列表项的其他字符串参数,所有字符串参数都被传递但只有列表参数在web api中变为null。这是我的代码。

    public class CourseDetails
    {                       
        public string Name { get; set; }
        public string Price { get; set; }
        public string Domain { get; set; }            

        public List<SuggestedAndFAQ> SuggestedReadingList { get; set; }
        public List<SuggestedAndFAQ> FAQList { get; set; }            
    }

    [HttpPost]
    public string SaveCourse([FromBody] CourseDetails CD)
    {
        string strResult = "N";
        using(ICALMSAdminEntities db= new ICALMSAdminEntities())
        {
          // My code
        }
    }

调用web api ...

public string SaveCourse(CourseDetails CD)
    {
        string uri1 = "http://xxx/myWebApi";
        using (WebClient wc = new WebClient())
        {
            string newUri = uri1 + "/SaveCourse";                
            string myParameters = "Name=" + CD.Name + "&Domain=" + CD.Domain + "&Price=" + CD.Price+ "&SuggestedReadingList=" + CD.SuggestedReadingList + "&FAQList=" + CD.FAQList;
            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            return JsonConvert.DeserializeObject<string>(wc.UploadString(newUri, myParameters));
        }
    }

1 个答案:

答案 0 :(得分:0)

实际上,您没有以正确的格式(JSON)发布数据。您可以将PostAsJsonAsync方法与WebClient一起使用,如:

CourseDetails classDetails= CourseDetails
{
// set data in CourseDetails instance
};

string uri1 = "http://xxx/myWebApi";
        using (WebClient wc = new WebClient())
        {
var response = wc.PostAsJsonAsync(uri1, classDetails).Result;

// other stuff

return  response.Content.ReadAsAsync<CourseDetails>().Result;

}