C# HttpResponseMessage到字符串

C# HttpResponseMessage到字符串,c#,C#,我正在调用一个返回Task的方法,在调用方法中,我需要读取字符串形式的响应 下面是我写的代码: static public async Task<HttpResponseMessage> Validate(string baseUri,HttpContent content) { HttpResponseMessage response = new HttpResponseMessage(); response = await client.PostAsync(

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

下面是我写的代码:

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;
}
静态公共异步任务验证(字符串baseUri、HttpContent){
HttpResponseMessage response=新的HttpResponseMessage();
response=wait client.PostAsync(baseUri,content);
返回响应;
}
公共字符串测试(){
字符串postJson=“{Login=\“user\”,Password=\“pwd\”}”;
HttpContent-stringContent=新的stringContent(postJson,
unicodeincode.UTF8,“应用程序/json”);
HttpResponseMessage结果=验证(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'
无法隐式转换类型
“System.Threading.Tasks.Task”到
'System.Net.Http.HttpResponseMessage'
  • 仅为了可读性,将方法名称从
    Validate(..)
    更改为
    validateSync(..)
    。只是为了明确这个方法返回一个任务,您必须等待它

  • 调用Validate方法时缺少等待。如果您不希望或可以使调用方异步,那么使用方法
    GetAwaiter().GetResult()
    ,您将得到您想要的

  • ReadAsStringAsync().Result
    替换为
    ReadAsStringAsync().GetAwaiter().GetResult()

  • 像其他人在注释中写的那样,调用
    。Result
    是不好的,因为它可能导致锁定。这通常也适用于
    GetAwaiter().GetResult()
    ,但调用它们比调用
    Result
    更可取。最好的选择是使用
    wait/async

    当您想知道
    GetAwaiter().GetResult()与调用
    Result
    之间的区别时,您可以阅读以下内容: 您的问题在于:

    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();
    }
    
    静态公共异步任务验证(字符串baseUri、HttpContent)
    {  
    返回wait client.PostAsync(baseUri,content);
    }
    公共异步任务测试()
    {
    var postJson=“{Login=\“user\”,Password=\“pwd\”}”;
    var stringContent=newstringcontent(postJson,unicodeincoding.UTF8,“application/json”);
    var结果=等待验证(Uri、stringContent);
    
    返回wait result.Content.ReadAsStringAsync(); }

    与您的编码风格保持一致。至于为什么调用
    .Result
    不好,正如人们在评论中指出的那样,请检查。

    方法
    验证
    返回任务并且是异步的。基本上,您可以用两种不同的方式调用此方法:

    1) 在另一个异步方法中等待
    Validate
    的结果,如下所示

    public async Task<string> test() {
        string postJson = "{Login = \"user\", Password =  \"pwd\"}";
        HttpContent stringContent = new StringContent(postJson, 
            UnicodeEncoding.UTF8, "application/json");
        HttpResponseMessage result = await Validate(Uri,stringContent);
        var json = result.Content.ReadAsStringAsync().Result;
    }
    
    public string test() {
        string postJson = "{Login = \"user\", Password =  \"pwd\"}";
        HttpContent stringContent = new StringContent(postJson, 
            UnicodeEncoding.UTF8, "application/json");
        HttpResponseMessage result = Validate(Uri,stringContent).Result;
        var json = result.Content.ReadAsStringAsync().Result;
    }
    
    默认情况下选择第1种方式,除非您确实有阻止调用线程的冲动

    请注意,在WinForms、WPF或ASP.NET应用程序中使用第二个解决方案时,可能会出现死锁。这样修改
    Validate
    方法可以解决问题:

    response = await client.PostAsync(baseUri,content).ConfigureAwait(false);
    

    尝试HttpResponseMessage result=Validate(Uri,stringContent)@auburg:这种方式可能会阻塞。在这种情况下,OP需要等待调用ValidateCalling
    。由于可能存在锁,因此结果不好。是的,但这是一个完全不同的问题。重新设计他的代码不是我的责任:)@swdon:但你可以在答案中反映出来。请记住,SO不仅是OP的直接知识来源,也是今年以后来访的其他人的知识来源。答案表明可能存在的错误方法肯定可以改进。return wait result.Content.ReadAsStringAsync();-我可以将其转换为普通字符串吗?
    返回result.Content.ReadAsStringAsync().result