Search code examples
http-redirectdotnet-httpclientasp.net-core-webapiflurl

Disable AutoRedirect in FlurlClient


I am using FlurlHttp and I want to disable AllowAutoRedirect for some API calls. I know How can I get System.Net.Http.HttpClient to not follow 302 redirects?

WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.AllowAutoRedirect = false;
HttpClient httpClient = new HttpClient(webRequestHandler);
// Send a request using GetAsync or PostAsync
Task<HttpResponseMessage> response = httpClient.GetAsync("http://www.google.com")

But for Flurl I found only the way similar to described in C# Flurl - Add WebRequestHandler to FlurlClient (I haven't compiled yet the code below , so it may have some errors)

public class HttpClientFactoryWithWebRequestHandler : DefaultHttpClientFactory
{
    private readonly WebRequestHandler _webRequestHandler;

    public HttpClientFactoryWithWebRequestHandler (WebRequestHandler webRequestHandler ) 
    {
        _webRequestHandler = webRequestHandler ;
    }

    public override HttpMessageHandler CreateMessageHandler()
    {
        var handler =_webRequestHandler ;
//Or    var handler = new WebRequestHandler(_webRequestHandler );
        return handler;
    }
}

Then I can pass the setting for a new FlurlClient:

WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.AllowAutoRedirect = false;
var fc = new FlurlClient(url)
    .ConfigureClient(c => c.HttpClientFactory = 
                  new HttpClientFactoryWithWebRequestHandler (webRequestHandler));

It looks more complicated that it could be. Is it the right way to do or it can be done simplier?

UPDATE 2021: Flurl now supports out of the box

await url.WithAutoRedirect(false).GetAsync();

See more options in https://flurl.dev/docs/configuration/#redirects


Solution

  • Flurl now supports this natively:

    "https://example.com"
      .WithAutoRedirect(false)
      [...]
    

    Documentation: https://flurl.dev/docs/configuration/#redirects