C# httpClient GET调用不允许我返回值

C# httpClient GET调用不允许我返回值,c#,asp.net,asp.net-web-api,C#,Asp.net,Asp.net Web Api,我正在使用httpclient进行api调用,但当使用async时,该类只能是无效的,因此我试图找出如何将值返回到控制器并返回到视图 public async void GetResult(){ using(var httpClient = new HttpClient()){ var httpResponse = await httpClient.GetAsync(requestMessage); var responseContent = await httpResponse.Conte

我正在使用httpclient进行api调用,但当使用async时,该类只能是无效的,因此我试图找出如何将值返回到控制器并返回到视图

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

现在我有了responseContent(值),我想将它返回给我的控制器,但每次我尝试删除void时,它都会说async仅对void有效。

如果使用async方法,返回值应该始终是一个
任务。因此,如果您的响应内容是
字符串
,则您的代码如下所示:

public async Task<string> GetResult(){
    using(var httpClient = new HttpClient()){
        var httpResponse = await httpClient.GetAsync(requestMessage);
        return await httpResponse.Content.ReadAsStringAsync();
    }
}
public异步任务GetResult(){
使用(var httpClient=new httpClient()){
var httpResponse=await httpClient.GetAsync(requestMessage);
return wait httpResponse.Content.ReadAsStringAsync();
}
}

异步方法的返回类型必须为void、
Task
Task

public异步任务GetResult(){
使用(var httpClient=new httpClient()){
var httpResponse=await httpClient.GetAsync(requestMessage);
var responseContent=wait-httpResponse.Content.ReadAsStringAsync();
返回响应内容;
}
}

当我使用任务时,等待永远不会完成,但当我使用void时,数据返回到responseContent。它点击var httpResponse=wait。。。永远不会结束@Ion SapovalThat关于ASP.NET中的HttpClient的问题以下问题可以提供更多细节:非常感谢Kenneth,我不知道你是否从之前的评论中收到了我的@,但我解释说,当我使用Task时,数据永远不会出现,但当我使用void时,它会以responseContent的值结束。在这三个选项中,只有在非常有限的情况下,它才应该是
void
(例如,无法返回值的事件处理程序)。
 public async Task<string> GetResult(){
    using(var httpClient = new HttpClient()){
      var httpResponse = await httpClient.GetAsync(requestMessage);
      var responseContent = await httpResponse.Content.ReadAsStringAsync();
      return responseContent;
}

}