Skip to content

Commit

Permalink
Fixed a bug causing duplicate user-agent headers when using a shared …
Browse files Browse the repository at this point in the history
…`HttpClient`. (#2008)

* Added product version to the user-agent check when configuring HttpClient.

* Created a unit test to handle duplicate user agent scenario.
  • Loading branch information
tacosontitan committed Mar 12, 2023
1 parent 9ca6777 commit 41bff69
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/RestSharp/RestClient.cs
Expand Up @@ -210,7 +210,7 @@ public partial class RestClient : IRestClient {
static void ConfigureHttpClient(HttpClient httpClient, RestClientOptions options) {
if (options.MaxTimeout > 0) httpClient.Timeout = TimeSpan.FromMilliseconds(options.MaxTimeout);

if (options.UserAgent != null && httpClient.DefaultRequestHeaders.UserAgent.All(x => x.Product?.Name != options.UserAgent)) {
if (options.UserAgent != null && httpClient.DefaultRequestHeaders.UserAgent.All(x => $"{x.Product?.Name}/{x.Product?.Version}" != Options.UserAgent)) {
httpClient.DefaultRequestHeaders.TryAddWithoutValidation(KnownHeaders.UserAgent, options.UserAgent);
}

Expand Down
15 changes: 15 additions & 0 deletions test/RestSharp.Tests/RestClientTests.cs
Expand Up @@ -116,4 +116,19 @@ public class RestClientTests {

client1.HttpClient.Should().NotBeSameAs(client2.HttpClient);
}

[Fact]
public void ConfigureHttpClient_does_not_duplicate_user_agent_for_same_client() {
// arrange
var httpClient = new HttpClient();
var clientOptions = new RestClientOptions();

// act
var restClient1 = new RestClient(httpClient, clientOptions);
var restClient2 = new RestClient(httpClient, clientOptions);

// assert
Assert.Contains(httpClient.DefaultRequestHeaders.UserAgent, agent => $"{agent.Product.Name}/{agent.Product.Version}" == clientOptions.UserAgent);
Assert.Single(httpClient.DefaultRequestHeaders.UserAgent);
}
}

0 comments on commit 41bff69

Please sign in to comment.