2

I'm using httpclient to make api call but when using async the class can only be void so I am trying to figure out how to return a value to my Controller and back to the view.

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

Now that I have the responseContent(value) I want to return it to my controller but every time I try to remove the void it says async only works with void.

Rethabile
  • 325
  • 3
  • 22

2 Answers2

1

If you have async method the return value should always be a Task<T>. So if you response content is a string, your code would look like this:

public async Task<string> GetResult(){
    using(var httpClient = new HttpClient()){
        var httpResponse = await httpClient.GetAsync(requestMessage);
        return await httpResponse.Content.ReadAsStringAsync();
    }
}
Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • When I use Task the await never finishes but when I use void the data is returned to responseContent.It hits var httpResponse = await... and never finishes. @Ion Sapoval – Rethabile Feb 09 '16 at 23:48
  • 2
    That's an issue with the HttpClient in ASP.NET The following questions can provide more details: http://stackoverflow.com/questions/9895048/async-call-with-await-in-httpclient-never-returns http://stackoverflow.com/questions/10343632/httpclient-getasync-never-returns-when-using-await-async – Kenneth Feb 09 '16 at 23:56
  • Thank you so much Kenneth, for the help and the link to the other post. – Rethabile Feb 10 '16 at 00:04
0

The return type of an async method must be void, Task or Task<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;
}

}
mason
  • 31,774
  • 10
  • 77
  • 121
Ion Sapoval
  • 635
  • 5
  • 8
  • I don't know if you received my @ from an earlier comment but I was explaining that when I use Task the data never comes but when I use void it finishes with a value for responseContent. – Rethabile Feb 09 '16 at 23:53
  • 1
    And of the three, it should only be `void` in very limited circumstances (such as event handlers that can't return a value). – Jon Hanna Feb 10 '16 at 01:51