set user agent for all HttpClients from IHttpClientFactory

This commit is contained in:
Cucumberrbob 2025-06-14 13:34:15 +01:00
parent cb29187f72
commit 0461058d86
No known key found for this signature in database
GPG key ID: 2B935C47401C3614
2 changed files with 12 additions and 5 deletions

View file

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

View file

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