diff --git a/EasyPost.Tests/ClientTest.cs b/EasyPost.Tests/ClientTest.cs index 1e3427e7..ece22d8a 100644 --- a/EasyPost.Tests/ClientTest.cs +++ b/EasyPost.Tests/ClientTest.cs @@ -1,4 +1,6 @@ using System; +using System.Linq; +using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -109,6 +111,51 @@ public void TestHttpClientOverride() Assert.Equal(httpClient, overrideClient.CustomHttpClient); } + [Fact] + public async void TestHttpClientCustomProxy() + { + const string proxyAddress = "localhost:8888"; + + // Define a custom proxy in a custom HttpClientHandler in a custom HttpClient + HttpClientHandler handler = new() + { + UseProxy = true, + Proxy = new WebProxy($"http://{proxyAddress}"), + }; + HttpClient httpClient = new(handler: handler); + + Client client = new(new ClientConfiguration(FakeApikey) + { + CustomHttpClient = httpClient, + }); + + Assert.Equal(httpClient, client.CustomHttpClient); + + // Assert that the proxy is set in the HttpClient by attempting to make a request (should fail due to invalid proxy address) + try + { + await client.Address.Create(new Parameters.Address.Create()); + Assert.Fail("Expected HttpRequestException"); + } + catch (HttpRequestException e) + { + // GitHub runner will reject the connection attempt, this is considered a pass + if (e.Message.Contains("No connection could be made because the target machine actively refused it")) + { + Assert.True(true); + } + else // Evaluate the error message + { +#if NET5_0_OR_GREATER + Assert.Equal($"Connection refused ({proxyAddress})", e.Message); +#else + // Message is inconsistent in .NET Framework, so just assert that the exception was thrown + Assert.True(true); +#endif + } + } + } + [Fact] public async Task TestRequestHooks() { diff --git a/README.md b/README.md index f7b1ff2b..b2a26074 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,28 @@ client.Hooks.OnRequestExecuting += (sender, args) => { /* ... */ }; client.Hooks.OnRequestExecuting -= OnRequestExecutingHandler; ``` +### Proxies + +If you need to use a proxy to make requests to the EasyPost API, you can define a custom `HttpClientHandler` on a custom `HttpClient` passed to the `ClientConfiguration` constructor. + +```csharp +// Define a custom HttpClientHandler with details about the proxy +HttpClientHandler handler = new() +{ + UseProxy = true, + Proxy = new WebProxy($"http://localhost:8888"), +}; + +// Define a custom HttpClient with the custom handler +HttpClient httpClient = new(handler: handler); + +// Pass the custom HttpClient to the ClientConfiguration constructor when creating a new EasyPost Client +Client client = new(new ClientConfiguration(FakeApikey) +{ + CustomHttpClient = httpClient, +}); +``` + ## Documentation API documentation can be found at: .