0

Can somebody help me how to post an array of type long to a WebApi.

I think I have to use PostAsync from HttpClient, but I am not sure how to put array to HttpContent.

This is my controller.

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

And this is how I am trying to consume 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);
}
}

And I am getting this exception

{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
}}
4

1 回答 1

2

Instead of using StringContent, you can use ObjectContent:

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

var task = client.PostAsync(
    "https://<uri>/api/orderprocessing/UpdateBatchesToReadyToShip",
    content:content);
于 2012-11-09T15:27:24.623 回答