问题
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