c# - 使用 UseSetting 覆盖配置

标签 c# .net asp.net-core .net-core configuration

我正在使用 .NET Core 2.2、默认模板并尝试使用 UseSetting 覆盖配置,但我无法使其工作。在配置中测试值设置为文件,我想在代码中使用相同的值覆盖它,然后在启动中我想获取覆盖的值。

(最初我试图添加 AzureKeyVaultProvider,但它对我不起作用,我以这个示例结束)

配置:

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

程序.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");
}

启动.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 适用于主机配置,该配置应用程序配置之前应用。在您的示例中,JSON 值会覆盖 UseSetting 值。 UseSetting 设置主机配置中的值,该值会被复制到应用程序配置中,然后被 JSON 值覆盖。

使用ConfigureAppConfigurationAddInMemoryCollection达到预期的结果:

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

通过此设置,调用 AddInMemoryCollection 时使用的值将覆盖 JSON、env 等中的所有其他值。

关于c# - 使用 UseSetting 覆盖配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57788495/

相关文章:

c# - 没有 DataMember 属性的 DataContract 序列化

c# - System.Security.CodeAccessPermission 在 .NET Core 3.1/.NET 5.0 中是否已过时?

c# - 如何以编程方式检查变量是否接近 x?

c# - TestContext 定义的目录的目的是什么?

c# - 如何使用复杂对象发出 GET 请求?

c# - 模拟 IIndex<TKey, TValue>

.net - 响应式扩展与事件聚合器

c# - HTTPWebResponse 原始响应,使用反射

json - 为什么返回的 JSON 的大数字在 pretty-print 时会四舍五入?

linux - Azure Powershell 模块 - Linux (.NET Core) 支持