Search code examples
c#httpclient

How can i wait until the response is returned before returning in http request c#?


I want to wait for the response to be returned before returning the result:

     private static async Task<object> GetTestFuncAppAsync()
    {
        var result = string.Empty;
        using (HttpClient client = new HttpClient())
        {                
            string requestUrl = <myurl>
            HttpResponseMessage response = await client.GetAsync(requestUrl);             
            if (response.IsSuccessStatusCode)
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                result = responseContent;                 
            }
            else
            {
            }
        }
        return result;
    }

How can i wait until the responseContent is read before return result ? What seems to be happening is the it calls client.GetAsync and the calls return result and there is garbage text in there . How can i wait until the response is finished ?


Solution

  • Looks like there shouldn't be any problems since you're already using async. Maybe try returning Task<string> instead of Task<object>? Maybe it's serializing weirdly in translation.