将Web Api作为HttpPost使用

时间:2012-11-09 12:43:22

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

有人可以帮助我如何将类型为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
}}

1 个答案:

答案 0 :(得分:2)

您可以使用ObjectContent:

,而不是使用StringContent
var content = new ObjectContent<long[]>(arr, new JsonMediaTypeFormatter());

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