Skip to content

HttpClientFactory doesn't respect lifetime of custom message handlers #36574

@DiamondDragon

Description

@DiamondDragon

Here is example of code i use:

            services.AddHttpClient(serviceName.ToLowerInvariant(), client =>
                {
                    client.BaseAddress = new Uri(serviceEndpoint.BaseAddress);
                    client.Timeout = TimeSpan.FromSeconds(serviceEndpoint.Timeout);

                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MessagePackSerializer.ContentType));
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                })
                .AddHttpMessageHandler<CorrelationIdHandler>()
                .AddHttpMessageHandler<RequestResponseLoggingHandler>() 
                .AddHttpMessageHandler<TrustedClientAuthenticationHandler>();

Handlers are registered as follows:

            services.AddTransient<CorrelationIdHandler>();
            services.AddTransient<RequestResponseLoggingHandler>();
            services.AddTransient<TrustedClientAuthenticationHandler>();

When first request is sent by HttpClient whole processing pipeline is created. When second request is sent neither of handlers is created. Handlers are already created as part of first request processing. After two minutes (e.g. default lifetime of handler) handlers are recreated.

Current behavior causes problem when handlers resolve dependencies from container. These transient dependencies become "locked" by handler instances. For example this may cause issue if handler injects authentication headers based on ASP.NET Core request principal. E.g. ClaimsPrincipal of first request is used for subsequent requests.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions