gpt4 book ai didi

azure - 在 Azure Functions 应用程序中存储 Azure ConnectionString 的位置

转载 作者:行者123 更新时间:2023-12-03 04:48:50 29 4
gpt4 key购买 nike

我制作了一个连接到 CosmosDB 的 Azure Functions 应用程序。我创建了以下类来检索 CosmosClient 实例:

public static class CosmosClientContext
{
private static readonly CosmosClient CosmosClient = GetCosmosClient();

public static CosmosClient GetCosmosClient()
{
return CosmosClient
//?? new CosmosClient("AccountEndpoint=https://mycosmosdb.documents.azure.com:443/;AccountKey=JkLv....etc;");
?? new CosmosClient("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6...etc");
}
}

正如您所看到的,我目前正在类中对 ConnectionString 进行硬编码,这显然不是最佳的。

我注意到我的项目中有一个 local.settings.json 文件。这是存储本地连接字符串的地方吗?如果是这样,我是否必须为此使用特定的键名称?或者我如何从中读取?

当我发布 Azure Functions 应用程序时,它是如何工作的?

那么如何才能使其在本地使用我的本地 ConnectionString,并在发布时自动使用远程 ConnectionString?

最佳答案

您将它们存储为环境变量。在本地,这些将位于 local.settings.json 中,在 Azure 上,它们将位于 Azure 门户中函数应用的“配置”边栏选项卡下的“应用程序设置”选项卡中。

变量的名称是任意的。你的 local.settings.json 看起来像这样:

{
"IsEncrypted": false,
"Values": {
"CosmosDbConnectionString": "[CONNECTION STRING HERE]"
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}

确保它位于“值”部分内。您只需使用 GetEnvironmentVariable 方法即可访问它:

Environment.GetEnvironmentVariable("CosmosDbConnectionString");

所以类似:

return new CosmosClient(Environment.GetEnvironmentVariable("CosmosDbConnectionString"));

您不需要任何逻辑即可在开发和生产之间切换。由于每个地方的环境变量不同,它会自动选取正确的连接字符串。

请注意,在门户中,请确保使用“应用程序设置”部分而不是“连接字符串”部分。这很令人困惑,但连接字符串部分仅用于函数上的 Entity Framework 。 enter image description here

关于azure - 在 Azure Functions 应用程序中存储 Azure ConnectionString 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63605016/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com