Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to get ConfigurePrimaryHttpMessageHandler working in typed injection #44873

Open
spence-ss opened this issue Feb 12, 2025 · 0 comments
Open
Labels
⌚ Not Triaged Not triaged

Comments

@spence-ss
Copy link

Describe the issue or suggestion

Not sure where to post this. I found issue #33309 while researching my problem so posting this where that one was.

Summary

I have an ASP.NET web api where I needed an HttpClient that did not follow redirects. So I configured my controller to have a client injected while configuring the message handler from this article

builder.Services.AddHttpClient<ClientController>().ConfigurePrimaryHttpMessageHandler(() =>
{
    return new HttpClientHandler
    {
        AllowAutoRedirect = false
    };
});

However, i was still receiving a 200 Ok response when hitting urls that I knew were to return 302.

I was only able to fix this by using the HttpClientFactory

builder.Services.AddHttpClient(
    "factoryName",
    client => { }).ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler
        {
            AllowAutoRedirect = false
        };
    });

I'm able to continue my project with the factory method, but it appears the configuration is ignored
on the original method.

Project Link

Sample project https://github.com/spence-ss/HttpClientTest

Project FIles

HttpClientTest.csproj

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

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
  </ItemGroup>

</Project>

Program.cs

using HttpClientTest;
using HttpClientTest.Controllers;



//Url that will return a redirect response
Settings.UrlToTest = "https://smile.amazon.com";


var builder = WebApplication.CreateBuilder(args);

// Configure controller for client factory
builder.Services.AddHttpClient(
    Settings.FACTORY,
    client => { }).ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler
        {
            AllowAutoRedirect = false
        };
    });

//Configure controller with http client directly
builder.Services.AddHttpClient<ClientController>().ConfigurePrimaryHttpMessageHandler(() =>
{
    return new HttpClientHandler
    {
        AllowAutoRedirect = false
    };
});


builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

Settings.cs

namespace HttpClientTest
{
    public static class Settings
    {

        public const string FACTORY = "HttpClientTest";
        public static string UrlToTest { get; set; }
    }
}

ClientController.cs

using Microsoft.AspNetCore.Mvc;

namespace HttpClientTest.Controllers
{
    [ApiController]
    [Route("client")]
    public class ClientController : ControllerBase
    {
        private readonly HttpClient _httpClient;

        public ClientController(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        [HttpGet]
        public async Task<ActionResult> GetStatus()
        {
            var res = await _httpClient.GetAsync(Settings.UrlToTest);
            return Ok($"Received {res.StatusCode} from {Settings.UrlToTest}");
        }
    }
}

FactoryController.cs

using Microsoft.AspNetCore.Mvc;

namespace HttpClientTest.Controllers
{

    [ApiController]
    [Route("factory")]
    public class FactoryController : ControllerBase
    {
        private readonly HttpClient _httpClient;

        public FactoryController(IHttpClientFactory factory)
        {
            _httpClient = factory.CreateClient(Settings.FACTORY);
        }


        [HttpGet]
        public async Task<ActionResult> GetStatus()
        {
            var res = await _httpClient.GetAsync(Settings.UrlToTest);
            return Ok($"Received {res.StatusCode} from {Settings.UrlToTest}");
        }
    }
}

@dotnet-policy-service dotnet-policy-service bot added the ⌚ Not Triaged Not triaged label Feb 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⌚ Not Triaged Not triaged
Projects
None yet
Development

No branches or pull requests

1 participant