简体   繁体   中英

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 IHttpClientFactory and 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM