Azure 未从 WebJob 读取连接字符串

gan*_*ers 0 c# azure azure-webjobs asp.net-core

我正在尝试使用我的 .NET Core 项目配置 Azure WebJob。每次我在 Azure 中执行作业时,它都会告诉我错误:

通过使用以下格式 DefaultEndpointsProtocol=https;AccountName=NAME;AccountKey=KEY 指向存储 Microsoft Azure WebJobs 运行时日志的 Microsoft Azure 存储帐户,确保在 Microsoft Azure 网站配置中设置名为 AzureWebJobsDashboard 的连接字符串。

这是我配置所有内容以及配置内容的代码:

    private static void ConfigureServices(IServiceCollection serviceCollection)
    {
        // Optional: Setup your configuration:
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();

        // add any interfaces that will be needed here
        serviceCollection.AddScoped<IBatchJobService, BatchJobService>();

        // executes the job
        serviceCollection.AddScoped<ExecuteBatchJobs, ExecuteBatchJobs>();

        // One more thing - tell azure where your azure connection strings are
        var connStringDashboard = configuration["ConnectionStrings:AzureWebJobsDashboard"];
        var connStringStorage = configuration["ConnectionStrings:AzureWebJobsStorage"];

        Environment.SetEnvironmentVariable("AzureWebJobsDashboard", connStringDashboard);
        Environment.SetEnvironmentVariable("AzureWebJobsStorage", connStringStorage);
    }
Run Code Online (Sandbox Code Playgroud)

这是 appsettings.json 文件:

{
  "ConnectionStrings": {
    "AzureWebJobsDashboard": "DefaultEndpointsProtocol=https;AccountName=xxxxxxxxxxx;AccountKey=mykey;",
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=xxxxxxxxxxx;AccountKey=mykey;"
  }
}
Run Code Online (Sandbox Code Playgroud)

我在“var connStringDashboard = ....”的本地代码中设置了一个断点,它正确地从 appsettings.json 读取值。

然后它通过环境变量设置连接字符串。

关于我在设置连接字符串时哪里出错的任何想法?由于某种原因,Azure 似乎无法从环境变量中读取它们。

Joe*_*Cai 5

您需要AzureWebJobsDashboard在 Web App应用程序设置边栏选项卡的门户中设置连接字符串。仪表板作为单独的站点扩展运行,无法访问appsettings.json.

将连接字符串添加到应用程序设置边栏选项卡上的连接字符串部分

您可以更改代码,以便将appsettings.json文件和 Azure 中的连接字符串Application Settings重命名为其他内容(例如WebJobsStorageWebJobsDashboard),然后它将起作用。

Environment.SetEnvironmentVariable("AzureWebJobsStorage", configuration.GetConnectionString("WebJobsStorage"));
Environment.SetEnvironmentVariable("AzureWebJobsDashboard", configuration.GetConnectionString("WebJobsDashboard"));
Run Code Online (Sandbox Code Playgroud)

更多细节,你可以参考这个问题