In the past I have talked about how the HttpClient is thread safe. This allows you to reuse the same HttpClient and be very efficient regarding how many ephemeral ports your application consumes.
Because the HttpClient and the HttpClientHandler both need to be thread safe, their properties become immutable after a request has been issued. If you are in a scenario where you need to change settings, such as whether or not the handler allows redirects, you will have to develop a little hack to work around the default behavior.
Below is a method where you can use reflection to set a private field and avoid the property setter from checking whether or not a request has been issued. This could cause thread safety issues, however with the current implementation of HttpCliehtHandler it is perfectly safe so long as only one thread is consume the client at a time.
HttpClientHandler Extension
public static class HttpClientHandlerExtensions
{
private static readonly FieldInfo AllowAutoRedirectFieldInfo =
typeof (HttpClientHandler).GetField(
"allowAutoRedirect",
BindingFlags.Instance | BindingFlags.NonPublic);
public static void SetAllowAutoRedirect(this HttpClientHandler handler, bool value)
{
AllowAutoRedirectFieldInfo.SetValue(handler, value);
}
}
Unit Test
public class HttpClientHandlerExtensionsTests
{
[Fact]
public async Task SetAllowAutoRedirectTest()
{
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.AllowAutoRedirect = true;
using (var response = await client.GetAsync("http://www.google.com"))
response.EnsureSuccessStatusCode();
Assert.Throws<InvalidOperationException>(() =>
{
handler.AllowAutoRedirect = false;
});
handler.SetAllowAutoRedirect(false);
}
}
}
Enjoy,
Tom