C# 如何将HttpClientHandler添加到url?

C# 如何将HttpClientHandler添加到url?,c#,dotnet-httpclient,flurl,C#,Dotnet Httpclient,Flurl,我有一个请求处理程序: var httpClientHandler = new HttpClientHandler { Proxy = new WebProxy(proxy.Address, proxy.Port), UseProxy = true }; 以及: 如何将请求处理程序添加到FlurlClient?创建您自己的ProxiedHttpClientFactory以覆盖CreateMessageHandler()方法: public class ProxiedHttpCl

我有一个请求处理程序:

var httpClientHandler = new HttpClientHandler
{
    Proxy = new WebProxy(proxy.Address, proxy.Port),
    UseProxy = true
};
以及:


如何将请求处理程序添加到FlurlClient?

创建您自己的
ProxiedHttpClientFactory
以覆盖
CreateMessageHandler()
方法:

public class ProxiedHttpClientFactory : DefaultHttpClientFactory
{
    private readonly string _proxyAddress;
    private readonly int _proxyPort;

    public ProxiedHttpClientFactory(string proxyAddress, int proxyPort)
    {
        this._proxyAddress = proxyAddress;
        this._proxyPort = proxyPort;
    }

    public override HttpMessageHandler CreateMessageHandler()
    {
        return new HttpClientHandler
        {
            Proxy = new WebProxy(this._proxyAddress, this._proxyPort),
            UseProxy = true
        };
    }
}
然后使用它:

var settings = new FlurlHttpSettings
{
    HttpClientFactory = new ProxiedHttpClientFactory("my.proxy.com", 8080)
};

var client = new FlurlClient(settings);
在现有的
Url
实例上:

var url = new Url(hostUrl)
               .AppendPathSegment(pathSegment)
               .ConfigureClient(settings => settings.HttpClientFactory = new ProxiedHttpClientFactory("my.proxy.com", 8080));
var url = new Url(hostUrl)
               .AppendPathSegment(pathSegment)
               .ConfigureClient(settings => settings.HttpClientFactory = new ProxiedHttpClientFactory("my.proxy.com", 8080));