Search code examples
.netweb-serviceswebservice-client.net-4.8

HttpClientFactory Create method not working in .Net Framework 4.8 HttpClient is working


I have the web service developed in .Net framework 4.8 and the httpRuntime targetFramework points to 4.0. When I change the targetFramework to 4.8 the Http calls either timing out or returning 403 Forbidden error. But it works with targetFramework 4.0. Also If i use HttpClient object it works.

Don't know what is the major difference between creating HttpClient object vs HttpClientFactory.Create() If anyone solved this issue or know the solution please share. Thanks in Advance.

Configuration (Web.Config) : Not working

  <httpRuntime targetFramework="4.8"/>

The Code am using to call the API (looks similar except the business logic.)

public async Task<string> TestMethodAsync()
{    
    HttpClientWrapper clientWrapper = new HttpClientWrapper();
    HttpResponseMessage response = clientWrapper.GetAsync("https://www.google.com").Result;
    return response.Content.ReadAsStringAsync().Result;   
}

public class HttpClientWrapper
{
    private readonly CustomDelegatingHandler _delegatingHandler = new CustomDelegatingHandler();
    public async Task<HttpResponseMessage> GetAsync(string requestUri)
    {
        using (var client = HttpClientFactory.Create(_delegatingHandler))
        {
            return await client.GetAsync(requestUri);
        }
    }   
    public class CustomDelegatingHandler : DelegatingHandler
    {         
                  
    }
}

 


Solution

  • Using ConfigureAwait(false) is fine, but the best solution is to go async all the way:

    public async Task<string> TestMethodAsync()
    {    
      HttpClientWrapper clientWrapper = new HttpClientWrapper();
      HttpResponseMessage response = await clientWrapper.GetAsync("https://www.google.com");
      return await response.Content.ReadAsStringAsync();
    }