Asp.net mvc 3 使用Web Api';作为HttpPost

Asp.net mvc 3 使用Web Api';作为HttpPost,asp.net-mvc-3,asp.net-mvc-4,asp.net-web-api,asp.net-mvc-areas,wcf-web-api,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.

有人能帮我把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);
}
}

您可以使用ObjectContent代替StringContent:

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

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

顺便说一句,我通过从客户端发送逗号分隔的字符串,然后在服务器端拆分为一个数组,实现了同样的效果。也许是这样helpful@aamirsajjad谢谢你的回复。我还发送逗号分隔的值。但是得到上面的错误。我是否还需要提及我的web api操作的参数名称?或者我需要使用任何序列化程序吗?谢谢回复。我做了改动,效果很好。
var content = new ObjectContent<long[]>(arr, new JsonMediaTypeFormatter());

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