It works: client service + server service + utility service to know server uri when app is running
This commit is contained in:
50
HttpClientSetupService.cs
Normal file
50
HttpClientSetupService.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user