c# - HttpResponseMessage 到字符串

标签 c#

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

这是我输入的代码:

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/

相关文章:

c# - 如何解决 Azure "Windows logins are not supported in this version of SQL Server"?

c# - 更改 .asp 文件样式 (css)

c# - 新手错误: XamlParseException occured in WPF application

c# - 当消息是部分消息时,SocketAsyncEventArgs和缓冲

c# - 数据类型转换的统一方法

c# - 如何清除调试器输出窗口 Visual Studio 2012

c# - 找不到路径的一部分 - ASP.net/C# 图片上传

c# - DateTime.ParseExact() 的问题

c# - 多页TIFF的分离性能

c# - Predicatebuilder group and or queries with inner outer