首页 > 解决方案 > 如何从 Asp.NET Core 3.1 启动类访问 launchSettings.json 中的`applicationUrl` 属性?

问题描述

我目前正在创建一个 Asp.NET Core 3.1 API 应用程序。在其中,我有一个launchSettings.json如下所示:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:61392",
      "sslPort": 44308
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "Key": "Value",
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Application.API": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "https://localhost:5001;http://localhost:5000"
    }
  }
}

特别是,我对获取applicationUrl此文件中定义的值感兴趣。不幸的是,除了通过 JSON 序列化直接加载文件并探测那里的值之外,我没有看到任何明显的方法来访问它们。

因此,我正在寻找一个更优雅的解决方案。有没有办法从Startup.Configure和/或Startup.ConfigureServices方法中访问这些值?

我正在考虑类似的事情:

public void Configure(IApplicationBuilder builder)
{
    var url = builder.ApplicationServices.GetRequiredService<IServerHostingEnvironment>().ApplicationUrl
}

作为参考,我确实看到了这个问题,但这似乎需要一个 HTTP 请求。就我而言,在发出请求之前,我仍在配置服务器。

如需进一步参考和上下文:我正在构建一个 .NET GitHub App 应用程序,并且正在制作 Smee.io 客户端的相应等价物,其 Javascript 代码可在此处找到

客户端接受一个source(通过服务器发送的事件)并将其发送到一个target. 我source弄清楚并配置了,但具有讽刺意味的是,我无法以明显和配置的方式访问和建立targetURL(applicationUrl如上所示)。

最后,我意识到我可以硬编码 in 中的值appSettings.json,但这意味着我将在两个地方保持相同的值——一个在appSettings.json一个在已经存在的launchSettings.json. 如果可能的话,我宁愿把它放在一个地方以减少维护负担。

标签: c#jsonasp.net-coreconfigurationenvironment

解决方案


我最近实际上正在寻找类似的东西。

事实证明,您可以通过查看环境变量来确定 Visual Studio 在调试会话期间(来自 launchSettings.json 中的 applicationUrl)将哪些 URL 传递给应用程序。

尽管请记住,这可能仅对使用 launchSettings.json 文件的 VStudio IDE 中的调试有用

var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS").Split(";");

推荐阅读