Search code examples
c#asp.netasp.net-mvcwebclient

How to use HttpClient without async


Hello I'm following to this guide

static async Task<Product> GetProductAsync(string path)
{
    Product product = null;
    HttpResponseMessage response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
    {
        product = await response.Content.ReadAsAsync<Product>();
    }
    return product;
}

I use this example on my code and I want to know is there any way to use HttpClient without async/await and how can I get only string of response?

Thank you in advance


Solution

  • Of course you can:

    public static string Method(string path)
    {
       using (var client = new HttpClient())
       {
           var response = client.GetAsync(path).GetAwaiter().GetResult();
           if (response.IsSuccessStatusCode)
           {
                var responseContent = response.Content;
                return responseContent.ReadAsStringAsync().GetAwaiter().GetResult();
            }
        }
     }
    

    but as @MarcinJuraszek said:

    "That may cause deadlocks in ASP.NET and WinForms. Using .Result or .Wait() with TPL should be done with caution".

    Here is the example with WebClient.DownloadString

    using (var client = new WebClient())
    {
        string response = client.DownloadString(path);
        if (!string.IsNullOrEmpty(response))
        {
           ...
        }
    }