ASP.NET Core数据库连接串的值为什么和appsettings.json配的不一样
这篇"ASP.NET Core数据库连接串的值为什么和appsettings.json配的不一样"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇"ASP.NET Core数据库连接串的值为什么和appsettings.json配的不一样"文章吧。
一、配置读取顺序
ASP.NET Core 中的配置是使用一个或多个配置提供程序执行的,配置提供程序使用各种配置源从键值对读取配置数据。
ASP.NET Core 提供了大量可用的配置提供程序,这还不包括可以自定义配置提供程序。
添加配置提供程序的顺序很重要,因为后面的提供程序添加的配置值将覆盖前面的提供程序添加的值。
配置提供程序的典型顺序为:
appsettings.jsonappsettings.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配置,返回结果正确。
以上就是关于"ASP.NET Core数据库连接串的值为什么和appsettings.json配的不一样"这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注行业资讯频道。