在 ASP.NET Core HostedService 中获取应用程序的基本 URL

Getting the Base URL of the application inside of the ASP.NET Core HostedService

我需要获取 HostedServices 之一内的 ASP.NET Core 应用程序的基本 URL。

我需要这个,因为它向托管它的同一个 ASP.NET 核心应用程序发出请求(目的是预热,以提高对用户的首次调用性能)。

目前我的解决方案是将基本 URL 保留在配置文件中或仅保留在托管服务私有变量中。

https://github.com/BBGONE/JRIApp.Core/blob/master/DEMOS/RIAppDemoMVC/RIAppDemo/Utils/WarmUpService.cs

但是我想,有一种方法可以从启动代码中获取它,但是我不知道它隐藏在哪里。

有人知道怎么获得吗?

附言- 有一些解决方案可以从请求信息中获取它,但是 HostedService 是在任何请求完成之前启动的。所以不适合这种情况。


我已经找到了如何获取应用程序的地址。

1
2
3
4
public void Configure(IApplicationBuilder application)
{
    var addresses = application.ServerFeatures.Get<IServerAddressesFeature>().Addresses;
}

虽然它有一个问题 https://github.com/aspnet/Hosting/issues/811 并且如果应用程序托管在 IIS 或 IIS Express 中则无法使用。

他们说:

That's not going to work for IIS or IIS Express. IIS is running as a
reverse proxy. It picks a random port for your process to listen on
and does not flow the public address information to you. The only way
to get the public address information is from incoming requests.

ASP.NET Core 模块生成动态端口以分配给后端进程。 CreateDefaultBuilder 调用 UseIISIntegration 方法。 UseIISIntegration 将 Kestrel 配置为侦听 localhost IP 地址 (127.0.0.1) 的动态端口。如果动态端口是 1234,Kestrel 会在 127.0.0.1:1234 侦听。此配置替换由.

提供的其他 URL 配置

但是如果你在构建后从 WebHost 获取该功能,那么这可以用于获取本地地址以进行预热。

我是这样试的:

1
2
3
4
5
6
7
8
9
 public static void Main(string[] args)
 {
            var builder = CreateWebHostBuilder(args);
            var webHost = builder.Build();
            var addresses = webHost.ServerFeatures.Get<IServerAddressesFeature>().Addresses;
            var address = addresses.FirstOrDefault();
            AppDomain.CurrentDomain.SetData("BaseUrl", address??"");
            webHost.Run();
  }

并在 WarmUpService 中获取本地 Kestrel 地址,如下所示:

1
string baseUrl = AppDomain.CurrentDomain.GetData("BaseUrl").ToString();