我正在使用FlurlHttp并且我想为某些 API 调用禁用 AllowAutoRedirect。我知道如何让 System.Net.Http.HttpClient 不遵循 302 重定向?
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")
但是对于 Flurl,我发现只有类似于 C# Flurl - Add WebRequestHandler to FlurlClient中描述的方式(我还没有编译下面的代码,所以它可能有一些错误)
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;
}
}
然后我可以传递新 FlurlClient 的设置:
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.AllowAutoRedirect = false;
var fc = new FlurlClient(url)
.ConfigureClient(c => c.HttpClientFactory =
new HttpClientFactoryWithWebRequestHandler (webRequestHandler));
它看起来可能更复杂。这是正确的方法还是可以更简单地完成?
2021 年更新:Flurl 现在支持开箱即用
await url.WithAutoRedirect(false).GetAsync()
;