gpt4 book ai didi

c# - HttpResponseMessage 到字符串

转载 作者:行者123 更新时间:2023-11-30 15:13:49 25 4
gpt4 key购买 nike

我正在调用一个返回任务的方法,在调用方法中我需要读取字符串形式的响应。

这是我输入的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com