Consuming Web Api's as HttpPost

╄→гoц情女王★ 提交于 2019-12-13 03:55:26

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/13308307/consuming-web-apis-as-httppost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!