Search code examples
c#asp.net-coreproxyflurl

How to specify a proxy for a Flurl client in version 4.0.x?


We're using Flurl v3.0.7 and Flurl.Http v3.2.4. To set up a proxy for a client, we use a helper class:

public class ProxyHttpClientFactory : DefaultHttpClientFactory {
    private readonly string _address;

    public ProxyHttpClientFactory
    (
        string address
    ) 
    {
        _address = address;
    }

    public override HttpMessageHandler CreateMessageHandler() 
    {
        return new HttpClientHandler 
        {
            Proxy = new WebProxy(_address),
            UseProxy = true
        };
    }
}

Then we call it like:

IFlurlClient restClient = new
    FlurlClient("https://your.server.com/api/v1/baseaddress")
        .Configure(settings => {
            settings.HttpClientFactory = 
                new ProxyHttpClientFactory("http://proxy.domain.com:port");});

DataOut out = await "https://your.server.com/api/v1/baseaddress/endpointaddress"
   .WithClient(restClient)
   .PostJsonAsync(in)
   .ReceiveJson<DataOut>();

How do you accomplish the same using Flurl 4.0.x? I found examples at https://flurl.dev/docs/configuration/?#message-handlers, but they do not resemble our current approach, so I'm not sure how to adapt them. Basically, I need to solve the same problem I posted at How to set up a proxy server for a flurl client selectively?, but now using Flurl 4.0.x.


Solution

  • This would be the most direct translation of your code to 4.0:

    var restClient = new FlurlClientBuilder("https://your.server.com/api/v1/baseaddress")
       .ConfigureInnerHandler(h => {
          h.Proxy = new WebProxy("http://proxy.domain.com:port");
          h.UseProxy = true;
       })
       .Build();
    
    DataOut out = await restClient
       .Request("endpointaddress")
       .PostJsonAsync(in)
       .ReceiveJson<DataOut>();