50 lines
1.7 KiB
C#
50 lines
1.7 KiB
C#
using Microsoft.AspNetCore.Hosting.Server;
|
|
using Microsoft.AspNetCore.Hosting.Server.Features;
|
|
|
|
namespace Sandbox;
|
|
|
|
public class HttpClientSetupService(
|
|
HttpClient httpClient,
|
|
IServer server,
|
|
IHostApplicationLifetime applicationLifetime)
|
|
: BackgroundService
|
|
{
|
|
private readonly HttpClient _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
|
|
private readonly IServer _server = server ?? throw new ArgumentNullException(nameof(server));
|
|
private readonly IHostApplicationLifetime _applicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime));
|
|
|
|
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
var applicationStartedToken = _applicationLifetime.ApplicationStarted;
|
|
if (applicationStartedToken.IsCancellationRequested)
|
|
{
|
|
ConfigureHttpClient();
|
|
}
|
|
else
|
|
{
|
|
applicationStartedToken.Register(ConfigureHttpClient);
|
|
}
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
private void ConfigureHttpClient()
|
|
{
|
|
var serverAddresses = _server.Features.Get<IServerAddressesFeature>();
|
|
var address = serverAddresses.Addresses.FirstOrDefault();
|
|
if (address == null)
|
|
{
|
|
// Default ASP.NET Core Kestrel endpoint
|
|
address = "http://localhost:5000";
|
|
}
|
|
else
|
|
{
|
|
address = address.Replace("*", "localhost", StringComparison.Ordinal);
|
|
address = address.Replace("+", "localhost", StringComparison.Ordinal);
|
|
address = address.Replace("[::]", "localhost", StringComparison.Ordinal);
|
|
}
|
|
|
|
var baseUri = new Uri(address);
|
|
_httpClient.BaseAddress = baseUri;
|
|
}
|
|
} |