首页 > 解决方案 > Azure Functions,如何拥有多个 .json 配置文件

问题描述

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

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

标签: c#azureazure-functionsasp.net-core-2.0

解决方案


我希望看到函数以与 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);
    }
}

推荐阅读