Search code examples
c#asp.net-coreasp.net-core-2.1

How to use WinHttpHandler with IHttpClientFactory in core2.1?


I'm trying to use the new IHttpClientFactory with an ASP.net Core 2.1 WEB API application.

public void ConfigureServices(IServiceCollection services)
{
    // other services configuration
    services.AddHttpClient();
}

In my ConfigureServices method, I don't see a way to add the IHttpClientFactoryand configure it to use WinHttpHandler.

The AddHttpClient methods that return a IHttpClientBuilder gives you access to methods that configure the HttpMessageHandler but those have to be derived from DelegatingHandler but WinHttpHandler does not derive from DelegatingHandler.

See no way to tell HttpClient to use WinHttpHandler when being constructed.


Solution

  • Figured it out.

    Thanks to tip given by @Nkosi in the comments!

    I solved this by using a named HttpClient when registering the HttpClient service and then configuring the message handler to use WinHttpHandler as the PrimaryHandler

    services.AddHttpClient<HttpClient>("WinHttp")
            .ConfigureHttpMessageHandlerBuilder(c =>
            {
                c.PrimaryHandler = new WinHttpHandler() { WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy };
            });
    

    Then when using the IHttpClientFactory, specify the name you gave when registering it.

    var httpClient = this._httpClientFactory.CreateClient("WinHttp");
    

    Your HttpClient will now use WinHttpHandler!

    NOTE To use WinHttpHandler you must add nuget package System.Net.Http.WinHttpHandler