c# - Azure Functions,如何拥有多个 .json 配置文件
问题描述
所以我写了一个在本地工作得很好的天蓝色函数。我相信这取决于拥有local.setting.json
文件。但是当我将它发布到天蓝色时,该功能不起作用,因为它找不到我定义的设置值。来自 Web 应用程序和控制台驱动的方法,我们将拥有与每个环境相关联的不同配置文件。我怎样才能让它工作,这样我就可以拥有多个settings.json
文件,例如一个用于开发、暂存和生产环境的文件?最终结果是使用 octopus deploy 进行部署,但是在这一点上,如果我什至不能让它与发布一起使用,那么就没有机会这样做。
我很困惑为什么这些信息不容易获得,因为假设这是一件常见的事情?
解决方案
我希望看到函数以与 asp.net 核心或控制台应用程序相同的方式支持特定于环境的设置。与此同时,我正在使用下面的代码,这有点 hacky(见评论)。
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
// Get the path to the folder that has appsettings.json and other files.
// Note that there is a better way to get this path: ExecutionContext.FunctionAppDirectory when running inside a function. But we don't have access to the ExecutionContext here.
// Functions team should improve this in future. It will hopefully expose FunctionAppDirectory through some other way or env variable.
string basePath = IsDevelopmentEnvironment() ?
Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot") :
$"{Environment.GetEnvironmentVariable("HOME")}\\site\\wwwroot";
var config = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false) // common settings go here.
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT")}.json", optional: false, reloadOnChange: false) // environment specific settings go here
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: false) // secrets go here. This file is excluded from source control.
.AddEnvironmentVariables()
.Build();
builder.Services.AddSingleton<IConfiguration>(config);
}
public bool IsDevelopmentEnvironment()
{
return "Development".Equals(Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT"), StringComparison.OrdinalIgnoreCase);
}
}
推荐阅读
- javascript - 如果参数不是字符串,期望类抛出错误?
- mongodb - 嵌套数组聚合
- webservice-client - 使用 Ws 导入创建客户端不生成服务和端口类
- html - 防止子元素上的框阴影
- c - 如何在 ubuntu 上使用 Makefile 编译 C 程序?
- javascript - 使用 node.js 从本地服务器检索响应数据
- three.js - THREE.js 添加子弹作为精灵并单独旋转每个
- java - gradle 4.9 - gradlew 和 java 10 仍然得到:无法从 '10' 确定 java 版本
- angularjs - angularjs复选框控制台中的响应不正确
- tensorflow - ValueError:使用序列设置数组元素。(TensorFlow) 成本函数