c# - 如何从 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
弄清楚并配置了,但具有讽刺意味的是,我无法以明显和配置的方式访问和建立target
URL(applicationUrl
如上所示)。
最后,我意识到我可以硬编码 in 中的值appSettings.json
,但这意味着我将在两个地方保持相同的值——一个在appSettings.json
一个在已经存在的launchSettings.json
. 如果可能的话,我宁愿把它放在一个地方以减少维护负担。
解决方案
我最近实际上正在寻找类似的东西。
事实证明,您可以通过查看环境变量来确定 Visual Studio 在调试会话期间(来自 launchSettings.json 中的 applicationUrl)将哪些 URL 传递给应用程序。
尽管请记住,这可能仅对使用 launchSettings.json 文件的 VStudio IDE 中的调试有用
var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS").Split(";");
推荐阅读
- shell - 在 vim 中编辑正在运行的程序
- javascript - 为什么 jquery video.trigger("play") 触发两次?
- react-native - 反应原生。为什么安卓模拟器这么慢?
- arrays - 属性数组的总和
- android - Flutter - 选定的项目移动到 ListView 的顶部
- javascript - JavaScript:将 div 的内容保存为 .txt 但保持格式化
- php - 警告:count() 在我的 single.php 中获取 wordpress 帖子的内容
- java - 如何使用正则表达式将字符串分成 n 个单词分组的部分并拆分?
- vb.net - 关于 Is 运算符的错误
- svn - 带有私钥身份验证的 Netbeans SVN