I'm trying to make some request via the FlurlClient
to some websites.
But I need to chain some methods that I wrote in a factory.
I use this approach to create the Proxy
and AllowAutoRedirect
factory.
AllowAutoRedirect Extension:
public static IFlurlClient AllowAutoRedirect(this IFlurlClient fc, bool allowAutoRedirect)
{
fc.Settings.HttpClientFactory = new CustomFlurlHttpClientFactory(allowAutoRedirect);
return fc;
}
Proxy Extension :
public static IFlurlClient Proxy(this IFlurlClient fc, DML.Proxy proxy)
{
fc.Settings.HttpClientFactory = new CustomFlurlHttpClientFactory(proxy);
return fc;
}
And finally this are my factory methods
private Proxy _proxy;
private bool? _allowAutoRedirect;
public CustomFlurlHttpClientFactory(Proxy proxy)
{
_proxy = proxy;
}
public CustomFlurlHttpClientFactory (bool? allowAutoRedirect)
{
_allowAutoRedirect = allowAutoRedirect;
}
public override HttpClient CreateHttpClient(HttpMessageHandler handler)
{
return base.CreateHttpClient(handler);
}
public override HttpMessageHandler CreateMessageHandler()
{
if(_proxy != null)
return ProxyClientHandlerConfiguration();
if (_allowAutoRedirect != null)
return AutoRedirectClientHandlerConfiguration();
return base.CreateMessageHandler();
}
private HttpClientHandler AutoRedirectClientHandlerConfiguration() => new HttpClientHandler { AllowAutoRedirect = _allowAutoRedirect ?? true };
private HttpClientHandler ProxyClientHandlerConfiguration() =>
new HttpClientHandler {
Proxy = new WebProxy {
Address = _proxy.GetFullUri(),
BypassProxyOnLocal = true,
UseDefaultCredentials = _proxy.UseDefaultCredentials()
},
UseProxy = true
};
But when the client is created, only the second method executes correctly (Proxy).
I understand that when I call AllowAutoRedirect
, it returns a new HttpClientHandler
, and when Proxy
gets called, it overrides the HttClientHandler
returned by AllowAutoRedirect
var cli = new FlurlClient(url)
.WithHeaders(headers)
.WithCookies(cookies)
.AllowAutoRedirect(false) /*Custom Factory Method*/
.Proxy(proxy) /*Custom Factory Method*/
.EnableCookies();
So, how can I get only one HttpClientHandler
using both methods, AllowAutoRedirect
and Proxy
?