c# - .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.
解决方案
您可以在以下位置使用依赖注入框架注册您的托管服务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
}
}
推荐阅读
- javascript - 如何通过 JavaScript 切换 Bootstrap 5 手风琴组件?
- boolean - 有没有一种简单的方法来检查所有变量是一起为真,还是一起为假?
- c# - 从固定数组转换为字节指针时出错
- python - 如何使用heroku从gmail帐户发送邮件?
- python - Python Regex:美国电话号码解析
- angular - 订阅内部的测试功能
- javascript - 将具有键值对的单个对象的数组转换为具有键值对的每个对象的对象数组
- android - 在 Android 设备中运行应用程序时字符串格式不起作用
- minio - MinIO 上传名称包含特殊字符的文件会发出 HTTP 403 Forbidden
- angular - 在 Docker 容器内切换运行在 NGINX 上的 Angular 应用程序的语言环境