我试图使用System.Net.Http.HttpClient发布多部分数据,获得的响应是200 ok。
这是我使用的方法:
public async Task postMultipart()
{
var client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");
// This is the postdata
MultipartFormDataContent content = new MultipartFormDataContent( );
content.Add(new StringContent("12", Encoding.UTF8), "userId");
content.Add(new StringContent("78", Encoding.UTF8), "noOfAttendees");
content.Add(new StringContent("chennai", Encoding.UTF8), "locationName");
content.Add(new StringContent("32.56", Encoding.UTF8), "longitude");
content.Add(new StringContent("32.56", Encoding.UTF8), "latitude");
Console.Write(content);
// upload the file sending the form info and ensure a result.
// it will throw an exception if the service doesn't return a valid successful status code
await client.PostAsync(fileUploadUrl, content)
.ContinueWith((postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
}
为了回应Jon(一个人并不简单地不同意Jon),不要将async / await世界与pre-async / await(ContinueWith
)世界混合在一起。
要将响应主体作为字符串获取,您需要第二个等待:
var response = await client.PostAsync(fileUploadUrl, content);
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
提示:你正在调用PostAsync
,等待结果......但是没有做任何事情。目前尚不清楚为什么你在使用ContinueWith
时,当你处于异步世界并且可以简单地处理它时:
var response = await client.PostAsync(fileUploadUrl, content);
response.EnsureSuccessStatusCode();
// Now do anything else you want to with response,
// e.g. use its Content property