In my ASP.NET Core web app I have an IHostedService object which performs some tasks periodically by using a timer.
Those tasks should retrieve the base server URL so I am trying this to do it:
Implemented StartAsync method:
public Task StartAsync(CancellationToken cancellationToken)
{
_hostApplicationLifetime.ApplicationStarted.Register(
() =>
{
_baseUrl = GetBaseUrl();
});
return Task.CompletedTask;
}
Where GetBaseUrl() method is:
private string GetBaseUrl()
{
ICollection<string>? addresses = _server.Features.Get<IServerAddressesFeature>()?.Addresses ?? null;
if (addresses != null && addresses.Count > 0)
{
return addresses.FirstOrDefault() ?? string.Empty;
}
return string.Empty;
}
After that code, the URL gotten by Addresses property is only one and strangely, it has a Kestrel port, My site is running under IISEXPRESS in port 44375.
How can I do it?
Of course, _server is a IServer and _hostApplicationLifetime is a IHostApplicationLifetime passed using DI into the hested service.