4

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.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Jim
  • 4,910
  • 4
  • 32
  • 50
  • 1
    Check this similar question asked recently https://stackoverflow.com/questions/50747749/how-to-use-httpclienthandler-with-httpclientfactory-in-net-core The suggested answer has promise based on what I have read in the source code for the builder. – Nkosi Jun 08 '18 at 13:50
  • Not what I needed but close, see my answer below. – Jim Jun 08 '18 at 14:19
  • 1
    Well I figured it would lead you in the right direction. Glad you figured it out. Happy coding. – Nkosi Jun 08 '18 at 14:20

1 Answers1

4

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

Jim
  • 4,910
  • 4
  • 32
  • 50