httpClient GET调用不允许我返回值

时间:2016-02-09 23:33:14

标签: c# asp.net asp.net-web-api

我正在使用httpclient进行api调用,但是当使用async时,类只能是void,所以我试图弄清楚如何将值返回到Controller并返回到视图。

public async void GetResult(){
using(var httpClient = new HttpClient()){
 var httpResponse = await httpClient.GetAsync(requestMessage);
 var responseContent = await httpResponse.Content.ReadAsStringAsync();
}
}

现在我有了responseContent(value)我想将它返回给我的控制器,但每次我尝试删除它时,它说async只适用于void。

2 个答案:

答案 0 :(得分:1)

如果您使用异步方法,则返回值应始终为Task<T>。因此,如果您的回复内容为string,则您的代码将如下所示:

public async Task<string> GetResult(){
    using(var httpClient = new HttpClient()){
        var httpResponse = await httpClient.GetAsync(requestMessage);
        return await httpResponse.Content.ReadAsStringAsync();
    }
}

答案 1 :(得分:0)

异步方法的返回类型必须为空TaskTask<T>

 public async Task<string> GetResult(){
    using(var httpClient = new HttpClient()){
      var httpResponse = await httpClient.GetAsync(requestMessage);
      var responseContent = await httpResponse.Content.ReadAsStringAsync();
      return responseContent;
}

}