2017-09-24 1 views
2

私はこの要求ハンドラがあります。URLにHttpClientHandlerを追加するには?

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

そして:私はFlurlClientに要求ハンドラを追加するにはどうすればよい

var url = new Url(hostUrl) 
    .AppendPathSegment(pathSegment); 

を?

答えて

2

CreateMessageHandler()方法より優先され、独自のProxiedHttpClientFactory作成:

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));