使用 KeyVault 时 Azure 存储 UseDevelopmentStorage=true
Azure Storage UseDevelopmentStorage=true when using KeyVault
我已将 API 配置为使用托管身份从 Azure KeyVault 获取 Azure 存储连接字符串。
现在的问题是,当我在 Visual Studio 中本地 运行 代码时,它不再使用来自 appsettings.development.json 的连接字符串,它是 "StorageAccount": "UseDevelopmentStorage=true"
因此在本地 运行ning 时我无法使用模拟器。
我在控制器中创建了以下条件来解决此问题:
public FileController(IConfiguration configuration, IWebHostEnvironment env)
{
this.configuration = configuration;
if (env.IsDevelopment())
{
conn = this.configuration.GetConnectionString("StorageAccount");
}
else
{
conn = this.configuration["StorageConnectionString"];
}
}
这是正确的做法吗?
在本地,如果您的 ASPNETCORE_ENVIRONMENT
设置为 Development
,那么它将读取您的本地存储帐户,例如 UseDevelopmentStorage=true
。
当您发布到 Azure 时,它将使用您的 Web 应用程序的 MSI 从 Key Vault 获取连接字符串。
更多详情,您可以参考以下代码:
private IConfiguration _configuration;
private IWebHostEnvironment _env;
public WeatherForecastController(IConfiguration configuration, IWebHostEnvironment env)
{
_configuration = configuration;
_env = env;
}
if (_env.IsDevelopment())
{
con = _configuration.GetSection("StorageAccount").Value;
}
else
{
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
con = keyVaultClient.GetSecretAsync("https://xxxx.vault.azure.net/secrets/xxxx").GetAwaiter().GetResult().Value;
}
我已将 API 配置为使用托管身份从 Azure KeyVault 获取 Azure 存储连接字符串。
现在的问题是,当我在 Visual Studio 中本地 运行 代码时,它不再使用来自 appsettings.development.json 的连接字符串,它是 "StorageAccount": "UseDevelopmentStorage=true"
因此在本地 运行ning 时我无法使用模拟器。
我在控制器中创建了以下条件来解决此问题:
public FileController(IConfiguration configuration, IWebHostEnvironment env)
{
this.configuration = configuration;
if (env.IsDevelopment())
{
conn = this.configuration.GetConnectionString("StorageAccount");
}
else
{
conn = this.configuration["StorageConnectionString"];
}
}
这是正确的做法吗?
在本地,如果您的 ASPNETCORE_ENVIRONMENT
设置为 Development
,那么它将读取您的本地存储帐户,例如 UseDevelopmentStorage=true
。
当您发布到 Azure 时,它将使用您的 Web 应用程序的 MSI 从 Key Vault 获取连接字符串。
更多详情,您可以参考以下代码:
private IConfiguration _configuration;
private IWebHostEnvironment _env;
public WeatherForecastController(IConfiguration configuration, IWebHostEnvironment env)
{
_configuration = configuration;
_env = env;
}
if (_env.IsDevelopment())
{
con = _configuration.GetSection("StorageAccount").Value;
}
else
{
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
con = keyVaultClient.GetSecretAsync("https://xxxx.vault.azure.net/secrets/xxxx").GetAwaiter().GetResult().Value;
}