简体   繁体   English

使用 UseSetting 覆盖配置

[英]Override configuration with UseSetting

I am using .NET Core 2.2, default template and trying to override configuration using UseSetting, however I can't make it work.我正在使用 .NET Core 2.2,默认模板并尝试使用 UseSetting 覆盖配置,但是我无法使其工作。 Test value set in config to File, I would like to override it with same value in Code, and then in Startup I want to get overridden value.将配置中的测试值设置为文件,我想在代码中用相同的值覆盖它,然后在启动中我想获得覆盖的值。

(Originally I was trying to add AzureKeyVaultProvider, but it was not working for me and I've ended with this example) (最初我试图添加 AzureKeyVaultProvider,但它对我不起作用,我以这个例子结束)

Configuration:配置:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Test": "file" 
}

Program.cs:程序.cs:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseSetting("Test", "code");
}

Startup.cs:启动.cs:

public class Startup
{
    private readonly IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var value = _configuration.GetValue<string>("Test");
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

UseSetting applies to the host configuration, which is applied before the application's configuration. UseSetting适用于主机配置,该配置在应用程序配置之前应用。 In your example, it's the JSON value that overrides the UseSetting value.在您的示例中,覆盖UseSetting值的是 JSON 值。 UseSetting sets the value in the host configuration, which gets copied into the application configuration and then overridden by the JSON value. UseSetting设置主机配置中的值,该值被复制到应用程序配置中,然后JSON 值覆盖

Use ConfigureAppConfiguration and AddInMemoryCollection to achieve the desired result:使用ConfigureAppConfigurationAddInMemoryCollection来达到想要的结果:

WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureAppConfiguration((ctx, configurationBuilder) =>
    {
        configurationBuilder.AddInMemoryCollection(new Dictionary<string, string>
        {
            ["Test"] = "code"
        });
    });

With this setup, values used in the call to AddInMemoryCollection override all other values in JSON, env, etc.通过此设置,调用AddInMemoryCollection使用的值会覆盖 JSON、env 等中的所有其他值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM