我正在调用一个返回任务的方法,在调用方法中我需要读取字符串形式的响应。
这是我输入的代码:
static public async Task<HttpResponseMessage> Validate(string baseUri,HttpContent content) {
HttpResponseMessage response = new HttpResponseMessage();
response = await client.PostAsync(baseUri,content);
return response;
}
public string test(){
string postJson = "{Login = \"user\", Password = \"pwd\"}";
HttpContent stringContent = new StringContent(postJson,
UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage result=Validate(Uri,stringContent);
var json = result.Content.ReadAsStringAsync().Result;
}
我期望是字符串,但抛出了这个错误:
Cannot implicitly convert type
'System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>' to
'System.Net.Http.HttpResponseMessage'
最佳答案
您的问题在:
HttpResponseMessage result=Validate(Uri,stringContent);
Validate
正在返回任务,而不是 HttpResponseMessage
。
将其更改为:
var result = Validate(Uri,stringContent).Result;
只是稍微清理一下代码并避免使用Result
,如果你能负担得起改变它的话:
static public async Task<HttpResponseMessage> Validate(string baseUri, HttpContent content)
{
return await client.PostAsync(baseUri,content);
}
public async Task<string> test()
{
var postJson = "{Login = \"user\", Password = \"pwd\"}";
var stringContent = new StringContent(postJson, UnicodeEncoding.UTF8, "application/json");
var result = await Validate(Uri,stringContent);
return await result.Content.ReadAsStringAsync();
}
与您的编码风格保持一致。至于为什么调用 .Result
是错误的,正如人们在评论中指出的那样,查看 this blog .
关于c# - HttpResponseMessage 到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57196900/