本文介绍了如何通过WebClient或HttpClient发布产品列表以及如何为它提供WebAPI控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有WebAPI控制器的方法:
I have WebAPI controller's method:
[HttpPost]
public void ChangeProducts(List<Product> products)
{
// ...
}
我尝试通过WebClient发送列表:
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);
}
或HttpClient:
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).
为什么?
推荐答案
我找到了解决方案。它有效:
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;
}
这篇关于如何通过WebClient或HttpClient发布产品列表以及如何为它提供WebAPI控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!