c# - Azure Functions,如何拥有多个 .json 配置文件

标签 c# azure azure-functions asp.net-core-2.0

所以我编写了一个在本地工作得很好的 azure 函数。我相信这取决于 local.setting.json 文件。但是当我将其发布到 azure 时,该函数不起作用,因为它找不到我定义的设置值。来自网络应用程序和控制台驱动的方法,我们将拥有与每个环境关联的不同配置文件。我怎样才能让它工作,这样我就可以拥有多个 settings.json 文件,例如一个用于开发、雄鹿和生产环境?最终结果是使用 octopus 部署来部署它,但在这一点上,如果我什至无法让它与发布一起工作,那么就没有机会这样做。

我很困惑为什么这些信息不容易获得,因为我认为这是常见的事情?

最佳答案

我希望看到函数以与 ASP.NET Core 或控制台应用程序相同的方式支持环境特定设置。与此同时,我正在使用下面的代码,这有点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);
    }
}

关于c# - Azure Functions,如何拥有多个 .json 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56457072/

相关文章:

azure - 如何在 ARM (JSON) 模板的 Azure 漏洞评估基线定义中指定多行?

Azure Function CosmosDb 绑定(bind)性能

Azure 计时器函数依赖注入(inject)

c# - 如何独立运行 nunit 测试

c# - 这个委托(delegate)用法的目的是什么?

javascript - 如何使用 LinkedIn API JavaScript SDK 获取访问 token

spring-boot - Azure Spring Boot : PKIX path building failed: sun. security.provider.certpath.SunCertPathBuilderException:

c# - 尝试在 Azure B2C 上更新用户时出现 "Insufficient Privileges"错误

c# - 如何从Azure Function更新服务总线消息?

c# - 允许搜索重音字符吗?