Disable AutoRedirect in FlurlClient

不想你离开。 提交于 2019-12-05 08:58:41

It feels a little heavy because it's a scenario that Flurl doesn't support directly, so it requires tinkering under the hood a bit. You're on the right track but I think there's a few ways you could simplify it. First, I'd suggest creating the WebRequestHandler inside the factory. Creating it externally and passing it in seems unnecessary.

public class NoRedirectHttpClientFactory : DefaultHttpClientFactory
{
    public override HttpMessageHandler CreateMessageHandler()
    {
        return new WebRequestHandler { AllowAutoRedirect = false };
    }
}

If you want this behavior app-wide by default, you could register it globally on startup. Then you don't need to do anything with individual FlurlClients.

FlurlHttp.Configure(settings =>
    settings.HttpClientFactory = new NoRedirectHttpClientFactory());

Otherwise, if you need the ability to pick and choose which FlurlClients you disable it for, an extension method would make it a little easier:

public static IFlurlClient WithoutRedirects(this IFlurlClient fc) {
    fc.Settings.HttpClientFactory = new NoRedirectHttpClientFactory();
    return fc;
}

Then use it like this:

new FlurlClient(url).WithoutRedirects()...

My implementation is based on Todd's answer (minor class/method name changes)

Example of use:

var resp = await new FlurlClient(url).DisableRedirects().Request().AllowAnyHttpStatus().GetAsync();
resp.StatusCode.Should().Be(HttpStatusCode.Found);//302

Implementation:

 public class HttpClientFactoryWithWebRequestHandler : DefaultHttpClientFactory
    {
        private readonly HttpMessageHandler _httpMessageHandler;
        public HttpClientFactoryWithWebRequestHandler(HttpMessageHandler httpMessageHandler) 
        {
            _httpMessageHandler = httpMessageHandler;
        }

        public override HttpMessageHandler CreateMessageHandler()
        {
            var handler = _httpMessageHandler;
            return handler;
        }
    }
    public static class FlurlClientExtensions
    {
        public static IFlurlClient DisableRedirects(this IFlurlClient fc)
        {
            var httpClientHandler = new HttpClientHandler {AllowAutoRedirect = false};
            fc.Settings.HttpClientFactory = new HttpClientFactoryWithWebRequestHandler(httpClientHandler);
            return fc;
        }
    } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!