From 0461058d862605272f25f6aa3ebbf2b8157e7628 Mon Sep 17 00:00:00 2001 From: Cucumberrbob <128094686+Cucumberrbob@users.noreply.github.com> Date: Sat, 14 Jun 2025 13:34:15 +0100 Subject: [PATCH] set user agent for all `HttpClient`s from `IHttpClientFactory` --- server/RdtClient.Service/DiConfig.cs | 13 +++++++++++-- .../Services/TorrentClients/TorBoxTorrentClient.cs | 4 +--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/server/RdtClient.Service/DiConfig.cs b/server/RdtClient.Service/DiConfig.cs index abe8af7..8a53391 100644 --- a/server/RdtClient.Service/DiConfig.cs +++ b/server/RdtClient.Service/DiConfig.cs @@ -1,5 +1,6 @@ using System.IO.Abstractions; using System.Net; +using System.Reflection; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.DependencyInjection; using Polly; @@ -15,6 +16,7 @@ namespace RdtClient.Service; public static class DiConfig { public const String RD_CLIENT = "RdClient"; + public static readonly String UserAgent = $"rdt-client {Assembly.GetEntryAssembly()?.GetName().Version}"; public static void RegisterRdtServices(this IServiceCollection services) { @@ -55,13 +57,20 @@ public static class DiConfig public static void RegisterHttpClients(this IServiceCollection services) { - services.AddHttpClient(); - var retryPolicy = HttpPolicyExtensions .HandleTransientHttpError() .OrResult(r => r.StatusCode == HttpStatusCode.TooManyRequests) .WaitAndRetryAsync(retryCount: 5, sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt))); + services.AddHttpClient(); + services.ConfigureHttpClientDefaults(builder => + { + builder.ConfigureHttpClient(httpClient => + { + httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent); + }); + }); + services.AddHttpClient(RD_CLIENT) .AddPolicyHandler(retryPolicy); } diff --git a/server/RdtClient.Service/Services/TorrentClients/TorBoxTorrentClient.cs b/server/RdtClient.Service/Services/TorrentClients/TorBoxTorrentClient.cs index 29ae9b3..4994e72 100644 --- a/server/RdtClient.Service/Services/TorrentClients/TorBoxTorrentClient.cs +++ b/server/RdtClient.Service/Services/TorrentClients/TorBoxTorrentClient.cs @@ -1,4 +1,3 @@ -using System.Reflection; using System.Diagnostics; using Microsoft.Extensions.Logging; using Newtonsoft.Json; @@ -24,8 +23,7 @@ public class TorBoxTorrentClient(ILogger logger, IHttpClien throw new("TorBox API Key not set in the settings"); } - var httpClient = httpClientFactory.CreateClient(); - httpClient.DefaultRequestHeaders.Add("User-Agent", $"rdt-client {Assembly.GetEntryAssembly()?.GetName().Version}"); + var httpClient = httpClientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromSeconds(Settings.Get.Provider.Timeout); var torBoxNetClient = new TorBoxNetClient(null, httpClient, 5);