Reputation: 325
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
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
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