silent_h
silent_h

Reputation: 153

.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.

Upvotes: 6

Views: 4242

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93063

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

Upvotes: 19

Related Questions