【问题标题】:Azure Storage UseDevelopmentStorage=true when using KeyVault使用 KeyVault 时 Azure 存储 UseDevelopmentStorage=true
【发布时间】:2020-06-24 01:45:51
【问题描述】:

我已将我的 API 配置为使用托管标识从 Azure KeyVault 获取 Azure 存储连接字符串。

现在的问题是,当我在 Visual Studio 中本地运行代码时,它不再使用来自 appsettings.development.json 的连接字符串 "StorageAccount": "UseDevelopmentStorage=true"

因此我在本地运行时无法使用模拟器。

我在控制器中创建了以下条件来解决此问题:

    public FileController(IConfiguration configuration, IWebHostEnvironment env)
    {
        this.configuration = configuration;

        if (env.IsDevelopment())
        {
            conn = this.configuration.GetConnectionString("StorageAccount");

        }
        else
        {
            conn = this.configuration["StorageConnectionString"];

        }
    }

这是正确的做法吗?

【问题讨论】:

    标签: azure azure-storage azure-keyvault


    【解决方案1】:

    在本地,如果您的ASPNETCORE_ENVIRONMENT 设置为Development,那么它将读取您的本地存储帐户,例如UseDevelopmentStorage=true

    当您发布到 azure 时,它​​将使用您的 webapp 的 MSI 从密钥保管库中获取连接字符串。

    更多细节可以参考以下代码:

    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;
    
    }
    

    【讨论】:

    • 这基本上就是我上面所做的。因此,您确认无法对 IsDevelopment 进行条件检查?
    • 是的,你必须这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2023-01-27
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多