Reading settings from Azure Configuration instead of appsettings.json in .NET 7 Web API.

huangapple go评论70阅读模式
英文:

Reading settings from Azure Configuration instead of appsettings.json in .NET 7 Web API

问题

我有一个.NET 7 Web API项目,我想从Azure配置中读取应用程序设置,而不是依赖传统的appsettings.json文件。

我之所以要这样做,是因为我正在使用Azure Key Vault来安全存储敏感配置值,如数据库连接字符串、API密钥和其他机密信息。通过利用Azure App Configuration,我可以直接引用存储在Azure Key Vault中的机密,使用@Microsoft.KeyVault(SecretUri={SecretURL})语法。

但目前它仅从appsettings.json加载, 请建议我需要进行哪些更改以从Azure App Configuration中读取设置。仅当在本地主机上运行时,它应从appsettings.json加载设置。

这是我的ConfigurationExtensions

public static class ConfigurationExtensions
{
    public static IConfigurationBuilder AddAppConfiguration(this IConfigurationBuilder configurationBuilder, IWebHostEnvironment hostingEnvironment)
    {
        configurationBuilder
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        // 对于本地主机,我们使用appsettings.json文件,当在本地主机上运行时,它不会被覆盖
        if (!hostingEnvironment.IsEnvironment("Localhost"))
        {
            configurationBuilder.AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
        }
        configurationBuilder.AddEnvironmentVariables();
        return configurationBuilder;
    }
}

这是我的Program.cs

var builder = WebApplication.CreateBuilder(args);
{
    // 环境配置
    var configuration = builder.Configuration;
    var env = builder.Environment;

    configuration.AddAppConfiguration(env);

    builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>());
    builder.Services.AddHttpClient();

    builder.Services.AddApplication();
    builder.Services.AddInfrastructure(builder.Configuration);

    builder.Services.AddHelpers();

    builder.Services.AddControllers()
       // 为控制器配置JSON序列化选项。
       .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        });

    builder.Services.Configure<ApiBehaviorOptions>(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });

}

var app = builder.Build();
{
    app.UseHttpsRedirection();

    // 认证与授权
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapControllers();

    app.UseRouting();
    app.UseSwaggerWithVersioning();
}

if (app.Environment.IsDevelopment())
{
    //DEV配置
}

app.Run();

希望这可以帮助你将应用程序设置从Azure App Configuration中读取。

英文:

I have a .NET 7 Web API project where I want to read application settings from Azure Configuration instead of relying on the traditional appsettings.json file.

The reason I want to do this is that I am using Azure Key Vault to securely store sensitive configuration values such as database connection strings, API keys, and other secrets. By leveraging Azure App Configuration, I can directly reference secrets stored in Azure Key Vault using the @Microsoft.KeyVault(SecretUri={SecretURL}) syntax.

Reading settings from Azure Configuration instead of appsettings.json in .NET 7 Web API.

But currently it is loading from appsettings.json only, Please suggest what changes I have to made to read settings from Azure App Configuration. It should load settings from appsettings.json only when running on localhost.

Reading settings from Azure Configuration instead of appsettings.json in .NET 7 Web API.

public static class ConfigurationExtensions
    {
        public static IConfigurationBuilder AddAppConfiguration(this IConfigurationBuilder configurationBuilder, IWebHostEnvironment hostingEnvironment)
        {
            configurationBuilder
                .AddJsonFile(&quot;appsettings.json&quot;, optional: false, reloadOnChange: true);

            // For Localhost, we&#39;re using appsettings.json file, it will not be overridden when running on Localhost
            if (!hostingEnvironment.IsEnvironment(&quot;Localhost&quot;))
            {
                configurationBuilder.AddJsonFile($&quot;appsettings.{hostingEnvironment.EnvironmentName}.json&quot;, optional: true, reloadOnChange: true);
                
            }
            configurationBuilder.AddEnvironmentVariables();
            return configurationBuilder;
        }
    }

This is my Program.cs

var builder = WebApplication.CreateBuilder(args);
{
    // Environment configuration
    var configuration = builder.Configuration;
    var env = builder.Environment;

    configuration.AddAppConfiguration(env);

    builder.Services.AddMediatR(cfg =&gt; cfg.RegisterServicesFromAssemblyContaining&lt;Program&gt;());
    builder.Services.AddHttpClient();

    builder.Services.AddApplication();
    builder.Services.AddInfrastructure(builder.Configuration);

    builder.Services.AddHelpers();

    builder.Services.AddControllers()
       // Configures the JSON serialization options for controllers.
       .AddJsonOptions(options =&gt;
        {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        });

    builder.Services.Configure&lt;ApiBehaviorOptions&gt;(options =&gt;
    {
        options.SuppressModelStateInvalidFilter = true;
    });

}

var app = builder.Build();
{
    app.UseHttpsRedirection();

    // Authentication &amp; Authorization
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapControllers();

    app.UseRouting();
    app.UseSwaggerWithVersioning();
}

if (app.Environment.IsDevelopment())
{
    //DEV configurations
}

app.Run();

答案1

得分: 1

如果您想从Azure应用配置服务加载设置,可以从Azure门户获取连接字符串。只需转到Azure门户中的您的应用配置服务,然后单击"访问密钥"。在右侧,您将看到连接字符串,类似于 Endpoint=https://appconfigurationstore.azconfig.io;Id=/Bd4;Secret=Dv9LqAonMWSKnOdOkJdY1gQpV1mkmDydWzVoYeOqvZk=

一旦获取到连接字符串,您可以使用以下代码:

public static class ConfigurationExtensions
{
    public static IConfigurationBuilder AddAppConfiguration(this IConfigurationBuilder configurationBuilder, IWebHostEnvironment hostingEnvironment)
    {
        configurationBuilder.AddAzureAppConfiguration(options =>
        {
            options.Connect("从门户获取的连接字符串")
        });
        return configurationBuilder;
    }
}

如果您不想使用连接字符串,您还可以利用托管标识(如果您的代码在Azure中运行)。您可以使用系统分配的标识或用户分配的标识。请注意,您用于连接的标识必须被分配适当的App配置RBAC角色(例如,App配置数据读取器)。在这种情况下,您将仅使用应用配置服务的终结点(https://appconfigurationstore.azconfig.io)。

在这种情况下,您的代码将如下所示:

options.Connect(new Uri("您的应用配置服务终结点"), new ManagedIdentityCredential("标识的客户端ID"));
英文:

If you want to load settings from Azure App Configuration service, you can get the connection string from Azure Portal. Just go to your App Configuration service in Azure Portal and click on "Access keys". On the right hand side you will see the connection string which would be something like Endpoint=https://appconfigurationstore.azconfig.io;Id=/Bd4;Secret=Dv9LqAonMWSKnOdOkJdY1gQpV1mkmDydWzVoYeOqvZk=.

Once you have it, you can use the following code:

public static class ConfigurationExtensions
{
    public static IConfigurationBuilder AddAppConfiguration(this IConfigurationBuilder configurationBuilder, IWebHostEnvironment hostingEnvironment)
    {
        configurationBuilder.AddAzureAppConfiguration(options =&gt; 
        {
            options.Connect(&quot;your-connection-string-from-portal&quot;)
        });
        return configurationBuilder;
    }
}

If you do not want to use connection string, you can also make use of Managed identity (if your code is running in Azure). You can either use System Assigned or User Assigned Managed Identity. Please note that the Identity you are using to connect must be assigned appropriate App Configuration RBAC role (e.g. App Configuration Data Reader). In this case, you will use the App Configuration service's endpoint (https://appconfigurationstore.azconfig.io) only.

Your code in that case would be:

options.Connect(new Uri(&quot;your-app-configuration-service-endpoint&quot;), new ManagedIdentityCredential(&quot;client-id-of-the-identity&quot;));

huangapple
  • 本文由 发表于 2023年6月1日 01:49:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定