部署后,Azure功能未绑定到应用程序设置

时间:2020-10-06 13:13:49

标签: azure azure-functions

我有一个使用Visual Studio用C#编写的Azure Function应用程序,使用3.0.9版的Functions SDK。在与csproj文件和host.json相同的目录中,我有一个appsettings.json文件,其内容如下:

{
    "test-queue": "test,
    "myOptions": {
      "batchSize": 5000
    }
}

当我在本地运行该函数时,该函数运行良好,但由于某种原因,在将其部署到Azure时,它似乎未绑定到appsettings文件。我使用以下启动类:

public class Startup : FunctionsStartup
{
    public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
    {
        builder.ConfigurationBuilder
            .SetBasePath(Environment.CurrentDirectory)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();

        var builtConfig = builder.ConfigurationBuilder.Build();
        var keyVaultName = builtConfig["AzureKeyVaultName"];

        if (!string.IsNullOrEmpty(keyVaultName))
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            builder.ConfigurationBuilder.AddAzureKeyVault($"https://{keyVaultName}.vault.azure.net/");
        }

        builder.ConfigurationBuilder
                .AddJsonFile("local.settings.json", true)
                .AddEnvironmentVariables()
                .Build();
    }

    public override void Configure(IFunctionsHostBuilder builder)
    {
        FunctionsHostBuilderContext context = builder.GetContext();
       
        builder.Services.AddOptions<MyOptions>()
            .Configure<IConfiguration>((settings, configuration) =>
            {
                configuration.GetSection("myOptions").Bind(settings);
            });
    }   
}

我有一个像这样的函数类:

public class MyFunction
{
    private readonly MyOptions options;

    public MyFunction(IOptions<MyOptions> options)
    {
        this.options = options.Value;
    }

    [FunctionName("Test")]
    public async Task Run(
        [QueueTrigger("%test-queue%")] MyParameters parameters,
        ILogger log)
    {
        log.LogInformation($"Batch size: {options.BatchSize}");
    }
}

麻烦的是,该函数似乎未使用appsettings文件。我在启动时收到InvalidOperationException,说“%test-queue%”不能解析为值。”我可以摆脱队列绑定,并对队列名称进行硬编码。这使功能运行正常,但是日志文件中显示批量大小为0而不是5000。

同样,它在本地运行时有效,但在部署时则无效。在启动过程中注册appsettings文件时,optional标志为false,因此必须找到它。

1 个答案:

答案 0 :(得分:0)

我已经通过替换得到了部分解决方案

builder.ConfigurationBuilder
        .SetBasePath(Environment.CurrentDirectory)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables();

使用

FunctionsHostBuilderContext context = builder.GetContext();

        builder.ConfigurationBuilder
            .AddJsonFile(Path.Combine(context.ApplicationRootPath, "appsettings.json"), optional: false, reloadOnChange: false)
            .AddEnvironmentVariables();

这仍然使我难以对队列名称进行硬编码,但至少已设置了batchSize变量。