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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With