Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core HttpClient - avoid auto redirect?

I'm using .NET Core 2.1 to consume some APIs. In my Startup.cs I configure a named HttpClient like this:

services.AddHttpClient("MyApi", client =>
{
    client.BaseAddress = new Uri("https://foo.com");
});

I would like to disable the automatic redirect following. I know you can do that when creating a new HttpClient by passing in a SocketsHttpHandler with AllowAutoRedirect = false. But when using the above factory pattern, I'm not seeing where I can configure this as I don't have access to the HttpClient's construction.

like image 491
silent_h Avatar asked Jul 12 '26 16:07

silent_h


1 Answers

The AllowAutoRedirect property belongs to the HttpMessageHandler. When using the AddHttpClient approach, you can configure the HttpMessageHandler itself using ConfigurePrimaryHttpMessageHandler. Here's an example of how to use this:

services
    .AddHttpClient("MyApi", client =>
    {
        client.BaseAddress = new Uri("https://foo.com");
    })
    .ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler()
        {
            AllowAutoRedirect = false
        };
    });

This is covered in the official docs: Configure the HttpMessageHandler

like image 77
Kirk Larkin Avatar answered Jul 15 '26 05:07

Kirk Larkin