ok, skoro to jest BackgroundService
to nie ma oczywiście HttpContext
. Może spróbuj w ten sposób?
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
private readonly IServer server;
public HomeController(IServer server)
{
this.server = server;
}
public IActionResult Index()
{
var addresses = server.Features.Get<IServerAddressesFeature>().Addresses;
Console.WriteLine($"Addresses from HomeController.Index: {string.Join(", ", addresses)}");
return View();
}
}
To przykład z kontrolerem, ale można to wstrzyknąć do innego serwisu
Źródło: https://swimburger.net/blog/dotnet/how-to-get-aspdotnet-core-server-urls
Edit: Sprawdziłem, u mnie działa:
builder.Services.AddHostedService<TimedHostedService>();
public class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger<TimedHostedService> _logger;
private System.Threading.Timer? _timer = null;
private readonly IServer _server;
public TimedHostedService(ILogger<TimedHostedService> logger, IServer server)
{
_logger = logger;
_server = server;
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service running.");
_timer = new System.Threading.Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object? state)
{
var addresses = _server.Features.Get<IServerAddressesFeature>().Addresses;
_logger.LogInformation($"Addresses: {string.Join(", ", addresses)}");
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
TimedHostedService: Information: Addresses: https://localhost:7246, http://localhost:5164
TimedHostedService: Information: Addresses: https://localhost:7246, http://localhost:5164
TimedHostedService: Information: Addresses: https://localhost:7246, http://localhost:5164