CSE_Random
CSE_Random

Reputation: 1

How to get HTTP response out of async Function

Hello I am trying to get the content of the HTTP response outside of this async function but can't return it because it is async. What should I do?

Here is the function:

    public async Task<HttpResponseMessage> GetResponse(string url)
    {
        using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false))
        using (HttpContent content = response.Content)
        {
            Console.WriteLine(content.ReadAsStringAsync().Result);
            return response;
        }
    }

Upvotes: 0

Views: 1850

Answers (1)

Johnathan Barclay
Johnathan Barclay

Reputation: 20373

Don't access Result, it will block the thread; use await instead:

Console.WriteLine(await content.ReadAsStringAsync());

To access the content outside the method:

var response = await GetResponse("url");
using (HttpContent content = response.Content)
{
    var contentString = await content.ReadAsStringAsync();
}

If you are returning the response, make sure you don't wrap it in a using block, or else it will be disposed before you have chance to read the content:

public async Task<HttpResponseMessage> GetResponse(string url)
{
    using (HttpClient client = new HttpClient())
    {
        return await client.GetAsync(url).ConfigureAwait(false);
    }
}

Or alternatively return the content directly from the method:

public async Task<string> GetContentAsync(string url)
{
    using (HttpClient client = new HttpClient())
    using (HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false))
    using (HttpContent content = response.Content)
    {
        return await content.ReadAsStringAsync();
    }
}

Upvotes: 2

Related Questions