【问题标题】:Consuming Web Api's as HttpPost使用 Web Api 作为 Http Post
【发布时间】:2012-10-29 18:52:54
【问题描述】:

有人可以帮我如何将 long 类型的数组发布到 WebApi。

我想我必须使用来自 HttpClient 的 PostAsync,但我不确定如何将数组放入 HttpContent。

这是我的控制器。

 [HttpPost]
 [Authorize]
 public void UpdateBatchesToReadyToShip(long[] batchIds)
 {
            // process request
  }

这就是我尝试使用 API 的方式

var buffer = Encoding.ASCII.GetBytes("username:password");
var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(buffer));
client.DefaultRequestHeaders.Authorization = authHeader;
var arr = new long[3];
arr[0] = 10;
arr[1] = 12;
arr[2] = 13;
HttpContent content = new StringContent(string.Join(",", from i in arr select i.ToString()));
var task = client.PostAsync("https://<uri>/api/orderprocessing/UpdateBatchesToReadyToShip",content:content);
if (task.Result.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("wrong credentials");
}
else
{
//task.Result.EnsureSuccessStatusCode();
HttpResponseMessage message = task.Result;
if (message.IsSuccessStatusCode)
{
var details = message.Content.ReadAsStringAsync().Result;
Console.Write(details);
}
}

我遇到了这个异常

{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Pragma: no-cache
  Cache-Control: no-cache
  Date: Fri, 09 Nov 2012 12:37:44 GMT
  Server: Microsoft-IIS/8.0
  X-AspNet-Version: 4.0.30319
  X-Powered-By: ASP.NET
  Content-Length: 1060
  Content-Type: application/json; charset=utf-8
  Expires: -1
}}

【问题讨论】:

  • 顺便说一句,我通过从客户端发送逗号分隔的字符串来实现相同的目的,然后在服务器端拆分为一个数组。可能有帮助
  • @aamirsajjad 感谢您的回复。我还发送逗号分隔值。但得到上述错误。我是否还需要提及我的 web api 操作的参数名称?还是我需要使用任何序列化程序?

标签: asp.net-mvc-3 asp.net-mvc-4 asp.net-web-api asp.net-mvc-areas wcf-web-api


【解决方案1】:

您可以使用 ObjectContent,而不是使用 StringContent:

var content = new ObjectContent<long[]>(arr, new JsonMediaTypeFormatter());

var task = client.PostAsync(
    "https://<uri>/api/orderprocessing/UpdateBatchesToReadyToShip",
    content:content);

【讨论】:

  • 感谢您的回复。我进行了更改,它工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-08
  • 2023-03-29
  • 2017-05-31
  • 1970-01-01
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多