简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM