How to POST list of Product by WebClient or HttpClient and how to whire WebAPI controller for it?

ⅰ亾dé卋堺 提交于 2019-12-11 22:24:28

问题


I have WebAPI controller's method:

    [HttpPost]
    public void ChangeProducts(List<Product> products)
    {
        // ...
    }

And I try to send a list by WebClient:

        using (var wc = new WebClient())
        {
            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

            string sl = JsonConvert.SerializeObject(products);
            var  r = wc.UploadString(_orderServiceUrl, sl);
        }

or by HttpClient:

        using (var hc = new HttpClient())
        {
            var val = JsonConvert.SerializeObject(products);

            hc.BaseAddress = new Uri(_orderServiceUrl);
            hc.DefaultRequestHeaders.Add("Accept", "application/json");
            HttpResponseMessage r = hc.PostAsync(_orderServiceUrl, new StringContent(val)).Result;
        }

But in controller the list is empty (not null, but no items).

Why?


回答1:


I found solution. It works:

using (var hc = new HttpClient())
{
    hc.BaseAddress = new Uri(_orderServiceUrl);
    hc.DefaultRequestHeaders.Accept.Clear();
    hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage response = hc.PostAsJsonAsync("", products).Result;
}


来源:https://stackoverflow.com/questions/26529339/how-to-post-list-of-product-by-webclient-or-httpclient-and-how-to-whire-webapi-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!