【问题标题】:How to POST list of Product by WebClient or HttpClient and how to whire WebAPI controller for it?如何通过 WebClient 或 HttpClient 发布产品列表以及如何为其连接 Web API 控制器?
【发布时间】:2014-10-23 13:34:36
【问题描述】:

我有 WebAPI 控制器的方法:

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

我尝试通过 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:

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

但在控制器中,列表是空的(不为空,但没有项目)。

为什么?

【问题讨论】:

  • 您确定您的列表包含元素吗?
  • @YuvalItzchakov,是的。有元素。
  • 请添加您的产品类声明并向我们展示生成的 JSON
  • {"CurrencyCode":null,"DeliveryKey":"X:1:2:1:1:23","EstimatedShippingDate":"2014-11-22T12:10:27.2342536Z", "GuaranteedShippingDate":"2014-10-23T12:10:27.2342536Z","OfferKey":"A0041:JS:HINO:AFL","OrderId":828,"Price":316.9100,"Quantity":1," QuantityLot":0,"QuantityUnit":null,"SellerOrderKey":null,"State":"NotAddedInBasket","StateComment":null,"UserId":2}
  • 它是JSON,与模型的属性名称相同。

标签: c# list http-post webclient asp.net-web-api


【解决方案1】:

我找到了解决方案。它有效:

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

【讨论】:

  • 不要使用Task.Result。它可能会导致死锁。使用WebClient查看同步api。
  • Tnx,但它是例如。我使用异步/等待方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多