一、配置读取顺序
ASP.NET Core 中的配置是使用一个或多个配置提供程序执行的,配置提供程序使用各种配置源从键值对读取配置数据。
ASP.NET Core 提供了大量可用的配置提供程序,这还不包括可以自定义配置提供程序。
添加配置提供程序的顺序很重要,因为后面的提供程序添加的配置值将覆盖前面的提供程序添加的值。
配置提供程序的典型顺序为:
appsettings.json appsettings.Environment.json 用户机密 环境变量 命令行参数假如, appsettings.json 配置了开发环境的数据库连接串, appsettings.Production.json 配置了生产环境的数据库连接串;管理员密码仅配置在用户机密中。
最终生产环境的配置为:
键 来源 数据库连接串 appsettings.Production.json 管理员密码 用户机密
二、分析
从 IConfigurationRoot 接口的文档上,可以了解到,IConfigurationRoot是表示 IConfiguration 层次结构的根。
使用 IConfigurationRoot.Providers 可以得到 IEnumerable ,猜测应该是顺序排列的。
然后反向遍历 Providers ,读取配置key对应的值,如果存在那应该就是配置的来源了。
让我们验证一下。
三、演示
1.读取Providers
创建WebApplication1,修改Startup.cs,代码如下:
public Startup(IConfiguration configuration) { ? ? Configuration = (IConfigurationRoot)configuration; } public IConfigurationRoot Configuration { get; } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { ? ? ...... ? ? app.UseEndpoints(endpoints => ? ? { ? ? ? ? ? ? endpoints.MapGet("/test", async context => ? ? ? ? ? ? { ? ? ? ? ? ? ? ? foreach(var provider in Configuration.Providers) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? await context.Response.WriteAsync(provider.ToString()); ? ? ? ? ? ? ? ? ? ? await context.Response.WriteAsync("\r\n"); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? }); ? ? }); ? ?? ? ? ...... }
从下图看到,顺序应该是正确的:
2.读取配置值
继续修改Startup.cs,代码如下:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { ? ? ...... ? ? app.UseEndpoints(endpoints => ? ? { ? ? ? ? endpoints.MapGet("/test2/{key:alpha}", async context => ? ? ? ? { ? ? ? ? ? ? var key = context.Request.RouteValues["key"].ToString(); ? ? ? ? ? ? foreach (var provider in Configuration.Providers.Reverse()) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? if (provider.TryGet(key, out string value)) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? await context.Response.WriteAsync(provider.ToString()); ? ? ? ? ? ? ? ? ? ? await context.Response.WriteAsync("\r\n"); ? ? ? ? ? ? ? ? ? ? await context.Response.WriteAsync(value); ? ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? }); ? ? }); ? ?? ? ? ...... }
运行后查找 AllowedHosts 配置,返回结果正确。
再次查找 AllowedHosts 配置,返回结果正确。
到此这篇关于为什么数据库连接串的值和 appsettings.json 配的不一样?的文章就介绍到这了,更多相关数据库连接串的值和appsettings.json配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于为什么ASP.NET Core 数据库连接串的值和appsettings.jso的详细内容...