In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
这篇"ASP.NET Core数据库连接串的值为什么和appsettings.json配的不一样"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇"ASP.NET Core数据库连接串的值为什么和appsettings.json配的不一样"文章吧。
一、配置读取顺序
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配置,返回结果正确。
以上就是关于"ASP.NET Core数据库连接串的值为什么和appsettings.json配的不一样"这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注行业资讯频道。
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.