Adding handler to default http client in ASP.NET Core [duplicate]

走远了吗. 提交于 2020-07-21 06:27:18

问题


Is there a way to add handlers to the default HTTP client in ASP.NET Core? Something like this?

.AddHttpClient()
.AddHttpMessageHandler<Handler1>()
.AddHttpMessageHandler<Handler2>();

回答1:


Documentation states that you can only add handlers or configure the inner most handler to named or typed clients.

Reference Configure the HttpMessageHandler

It may be necessary to control the configuration of the inner HttpMessageHandler used by a client.

An IHttpClientBuilder is returned when adding named or typed clients. The ConfigurePrimaryHttpMessageHandler extension method can be used to define a delegate. The delegate is used to create and configure the primary HttpMessageHandler used by that client:

services.AddTransient<Handler1>();
services.AddTransient<Handler2>();

services.AddHttpClient("configured-inner-handler")
    .AddHttpMessageHandler<Handler1>()
    .AddHttpMessageHandler<Handler2>();
    .ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler()
        {
            AllowAutoRedirect = false,
            UseDefaultCredentials = true
        };
    });



回答2:


Upon inspecting the source code of DefaultHttpClientFactory (which is both the IHttpClientFactory and the IHttpMessageHandlerFactory registered by AddHttpClient method), it turns out that there is no use registering a custom IHttpMessageHandlerFactory because DefaultHttpClientFactory never requires it (but directly uses its own method). Of course we could also register a custom IHttpClientFactory, but there is a easier way to achieve what we want.

The idea is that DefaultHttpClientFactory calls the transient service HttpMessageHandlerBuilder during its IHttpMessageHandlerFactory implementation, so all we have to do is to register a custom HttpMessageHandlerBuilder. For example:

public class CustomHttpMessageHandlerBuilder : HttpMessageHandlerBuilder {
    public override string Name { get; set; }
    public override HttpMessageHandler PrimaryHandler { get; set; }
    public override IList<DelegatingHandler> AdditionalHandlers => new List<DelegatingHandler>();
    // Our custom builder doesn't care about any of the above.
    public override HttpMessageHandler Build() {
        return new HttpClientHandler {
            // Our custom settings
        };
    }
}

And then register it:

services.AddTransient<HttpMessageHandlerBuilder, CustomHttpMessageHandlerBuilder>();

And it works.



来源:https://stackoverflow.com/questions/51642671/adding-handler-to-default-http-client-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!