我不完全确定发生了什么。 当我使用下面的代码并等待 HttpClient 时,我遇到了死锁并且响应永远不会返回。 如果我将等待放在
await response.Result.Content.ReadAsStringAsync()
上,那么响应将会返回,但是我不确定如何使用IsSuccessStatusCode
public async Task<string> PostAsyncJSONReadAsString(RESTInformation restInformation, string json)
{
var httpClient = GetHttpClient(restInformation);
var content = new StringContent(json, Encoding.UTF8, "application/json");
//this line Freezes
//var response = await httpClient.PostAsync(restInformation.Resource, content);
var response = httpClient.PostAsync(restInformation.Resource, content);
var resultContent = await response.Result.Content.ReadAsStringAsync();
/*if (response.IsSuccessStatusCode)
{
return resultContent;
}*/
return resultContent;
/*
if (response.IsSuccessStatusCode)
{
var contents = await response.Content.ReadAsStringAsync();
return contents;
}*/
//else return null;
}
不要使用
Task.Result
,基本上:
var response = await httpClient.PostAsync(restInformation.Resource, content);
var resultContent = await response.Content.ReadAsStringAsync();