Rethabile
Rethabile

Reputation: 325

httpClient GET call is not letting me return a value

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.

Upvotes: 2

Views: 2006

Answers (2)

Ion Sapoval
Ion Sapoval

Reputation: 635

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;
}

}

Upvotes: 0

Kenneth
Kenneth

Reputation: 28737

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();
    }
}

Upvotes: 1

Related Questions