【发布时间】:2021-11-20 07:59:40
【问题描述】:
我需要从 usersecrets 中获取连接字符串。我尝试过这样:
CosmosClient cosmos = new CosmosClient("CosmosConnectionString", new CosmosClientOptions
{
ConnectionMode = ConnectionMode.Gateway
});
但这不起作用,因为 CosmosClient 只能理解文字字符串。我尝试用 usersecrets 注入 Azure Functions,为此我创建了一个启动类:
[assembly: FunctionsStartup(typeof(Startup))]
namespace AltProject
{
public class Startup : FunctionsStartup
{
// override configure method
public override void Configure(IFunctionsHostBuilder builder)
{
var config = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json", true)
.AddUserSecrets(Assembly.GetExecutingAssembly(), false)
.AddEnvironmentVariables()
.Build();
builder.Services.AddSingleton<IConfiguration>(config);
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
Console.WriteLine(" {0} = {1}", de.Key, de.Value); // register your other services
}
}
}
然后我尝试在 CosmosClient 中以这种方式获取连接字符串:
CosmosClient cosmos = new CosmosClient(System.Environment.GetEnvironmentVariable("CosmosConnectionString", EnvironmentVariableTarget.Process), new CosmosClientOptions
{
ConnectionMode = ConnectionMode.Gateway
});
但这没有给我任何结果,似乎环境值没有注入用户机密。有没有办法让这个工作?
【问题讨论】:
标签: c# azure-functions azure-cosmosdb