docs icon indicating copy to clipboard operation
docs copied to clipboard

Unable to get ConfigurePrimaryHttpMessageHandler working in .net 6

Open codebuzz opened this issue 3 years ago • 3 comments

I have added a typed HttpClient through services and configured a handler like the following code on docs:

services.AddHttpClient("Named.Client")
    .ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler
        {
            AllowAutoRedirect = false,
            UseDefaultCredentials = true
        };
    });

However, the HttpClient injected into the class doesn't have these properties and isn't working properly. This is evident in the screen below:

image

Here AllowAutoRedirect is true which we seemingly set to false and the HttpClient isn't behaving as expected. Please check and let me know if I am missing something.


Document Details

⚠ Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.


Associated WorkItem - 57998

codebuzz avatar Jan 04 '23 10:01 codebuzz

Hi @codebuzz - I just tried this and I'm not able to recreate the issue that you're seeing. Are you able to share your exact code, so that I might help debug it with you? As of now, I'm fairly confident that this is perhaps a user error as I'm seeing the correct properties in the handler when debugging it locally.

Here is my code for a project I just put together:

configurehandler.csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <RootNamespace>ConfigureHttpHandler.Example</RootNamespace>
  </PropertyGroup>
  
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
  </ItemGroup>
  
</Project>

Todo.cs:

namespace Shared;

public record class Todo(
    int UserId,
    int Id,
    string Title,
    bool Completed);

Program.cs:

using Shared;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ConfigureHttpHandler.Example;

using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        const string name = "ConfigureHttpHandler.Example";
        services.AddHttpClient(
            name,
            client =>
            {
                // Set the base address of the named client.
                client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");

                // Add a user-agent default request header.
                client.DefaultRequestHeaders.UserAgent.ParseAdd("dotnet-docs");
            })
        .ConfigurePrimaryHttpMessageHandler(() =>
            {
                return new HttpClientHandler
                {
                    AllowAutoRedirect = false,
                    UseDefaultCredentials = true
                };
            });
        services.AddTransient<TodoService>();
    })
    .Build();

TodoService todoService =
    host.Services.GetRequiredService<TodoService>();

Todo[] todos = await todoService.GetUserTodosAsync(3);

ILogger logger =
    host.Services.GetRequiredService<ILogger<TodoService>>();

foreach (Todo? todo in todos)
{
    logger.LogInformation("Todo: {Details}", $"""
        Id: {todo?.Id} (Is completed: {todo?.Completed})
        Title: {todo?.Title}
        """);
}

await host.RunAsync();

TodoService.cs:

using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Shared;

namespace ConfigureHttpHandler.Example;

public sealed class TodoService
{
    private readonly IHttpClientFactory _httpClientFactory = null!;
    private readonly IConfiguration _configuration = null!;
    private readonly ILogger<TodoService> _logger = null!;

    public TodoService(
        IHttpClientFactory httpClientFactory,
        IConfiguration configuration,
        ILogger<TodoService> logger) =>
        (_httpClientFactory, _configuration, _logger) =
            (httpClientFactory, configuration, logger);

    public async Task<Todo[]> GetUserTodosAsync(int userId)
    {
        // Create the client
        const string name = "ConfigureHttpHandler.Example";
        using HttpClient client = _httpClientFactory.CreateClient(name);

        try
        {
            // Make HTTP GET request
            // Parse JSON response deserialize into Todo type
            Todo[]? todos = await client.GetFromJsonAsync<Todo[]>(
                $"todos?userId={userId}",
                new JsonSerializerOptions(JsonSerializerDefaults.Web));

            return todos ?? Array.Empty<Todo>();
        }
        catch (Exception ex)
        {
            _logger.LogError("Error getting something fun to say: {Error}", ex);
        }

        return Array.Empty<Todo>();
    }
}

When debugging this, my break point in the GetUserTodosAsync looks like this:

image

IEvangelist avatar Jan 04 '23 14:01 IEvangelist

Thanks for looking into this @IEvangelist. I am unable to post code due to company policies, however i have figured out the issue.

I was using the typed client like

services.AddHttpClient<MyService>().ConfigurePrimaryHttpMessageHandler....

It was fixed when i used

services.AddHttpClient<IMyService, MyService>().ConfigurePrimaryHttpMessageHandler.... 

and removed the separate registration of MyService.

The takeaway here is that Http Client still gets injected but the configure handler method is never called if we register only the implementation.

codebuzz avatar Jan 05 '23 05:01 codebuzz

Thank you @codebuzz! Using the generic method which specifies the interface in addition to the implementation fixed my problem. Were you able to find a reason why this worked? It feels like a bug to me.

Ignignokt avatar Jan 14 '25 04:01 Ignignokt