我的输入是一个字符串数组,我无法找到如何在C#.net
中异步发布请求string[] arr1 = new string[] { "one", "two", "three" };
client.BaseAddress = new Uri(this.baseServiceURL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(application/json));
var content = new StringContent(arr1.tostring());
//Make Rest API Get Method call
HttpResponseMessage response = client.PostAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
}
答案 0 :(得分:0)
试试这个
public async void AsyncPost()
{
string[] values= new string[] { "one", "two", "three" };
var content = JsonConvert.SerializeObject(new {
Values= values
});
using (var client = new HttpClient())
{
try
{
var httpResponseMessage = await client.PostAsync("http://SomeUrl.somewhere", content);
if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
{
// Do something...
}
}
catch (OperationCanceledException) { }
}
}
答案 1 :(得分:0)
如果您想将*
用作application/json
,则必须序列化您的输入。
我强烈建议您在客户端上使用Json.NET将数组序列化为json字符串:
Content-Type
作为替代方案,您可以手动序列化字符串数组:
var content = new StringContent(JsonConvert.SerializeObject(arr1), Encoding.UTF8, "application/json");
但我不鼓励你使用这种容易出错的方法。
根据您使用的.NET Framework版本,您可以添加var serialized = "[" + string.Join(",", arr1.Select(v => "\"" + v + "\"")) + "]";
var content = new StringContent(serialized, Encoding.UTF8, "application/json");
包并使用HttpClient.PostAsJsonAsync<T>
方法让框架完成繁重工作:
Microsoft.AspNet.WebApi.Client