Saturday, October 31, 2015

How to change HttpClientHandler.AllowAutoRedirect

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(
            BindingFlags.Instance | BindingFlags.NonPublic);
    public static void SetAllowAutoRedirect(this HttpClientHandler handler, bool value)
        AllowAutoRedirectFieldInfo.SetValue(handler, value);

Unit Test

public class HttpClientHandlerExtensionsTests
    public async Task SetAllowAutoRedirectTest()
        using (var handler = new HttpClientHandler())
        using (var client = new HttpClient(handler))
            handler.AllowAutoRedirect = true;
            using (var response = await client.GetAsync(""))
            Assert.Throws<InvalidOperationException>(() =>
                handler.AllowAutoRedirect = false;


No comments:

Post a Comment

Real Time Web Analytics