首页 > 解决方案 > .NET Core 3.0 IHostedService access web server URL - scheme, host, port etc

问题描述

The issue that I have is simple. I want to access the server URL in my IHostedService.

I cannot find a way to do it. There isn't any request there so I cannot use the IHttpContextAccessor.

IServer features property doesn't have any addresses and I am out of options.

I do not want to hard code the URL of the server in the configuration.

The version of .NET core that I am running is 3.0.

标签: c#.netasp.net-core.net-corekestrel-http-server

解决方案


您可以在以下位置使用依赖注入框架注册您的托管服务Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHostedService, MyHostedService>();
}

然后,您可以将一个注入IServer到您的托管服务中并使用以下方法获取地址IServerAddressesFeature

public class MyHostedService : IHostedService
{
    private readonly IServer _server;

    public MyHostedService(IServer server)
    {
       _server = server;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
       var features = _server.Features;
       var addresses = features.Get<IServerAddressesFeature>();
       var address = addresses.Addresses.FirstOrDefault(); // = http://localhost:5000
    }
}

推荐阅读