一:netcore读取配置文件(单个节点配置,得到的是字符串)
.netcore里面是没有web.config等xml文件,但是它是有appsettings.json,在发布后会生成到对应的项目中。如下图:
在framework项目中,我们晓得读取web.config文件,需要引用ConfigManager,然后是用ConfigurationManager.AppSettings[key]等方式读取,那么在.netCore该如何读取呢?
下面是appsettings.json的文件内容
1 { 2 "Logging": { 3 "LogLevel": { 4 "Default": "Warning" 5 } 6 }, 7 "option1": "value1_from_json", 8 "option2": 2, 9 "subsection": { 10 "suboption1": "subvalue1_from_json" 11 }, 12 "wizards": [ 13 { 14 "Name": "Gandalf", 15 "Age": "1000" 16 }, 17 { 18 "Name": "Harry", 19 "Age": "17" 20 } 21 ], 22 "AllowedHosts": "*" 23 }
读取的时候,其实.netCore已经有封装好的方法,我们直接拿来用就可以,下面在Startup下面进行调试监视Configuration,然后会发现如下图:
所以如果想要读取的时候可以通过可以来获取,如下代码:
Console.WriteLine($"option1 = {this.Configuration["Option1"]}"); Console.WriteLine($"option2 = {this.Configuration["option2"]}"); Console.WriteLine($"suboption1 = {this.Configuration["subsection:suboption1"]}"); Console.WriteLine("Wizards:"); Console.Write($"{this.Configuration["wizards:0:Name"]}, "); Console.WriteLine($"age {this.Configuration["wizards:0:Age"]}"); Console.Write($"{this.Configuration["wizards:1:Name"]}, "); Console.WriteLine($"age {this.Configuration["wizards:1:Age"]}");
只能通过key来获取对应的值。
然后我们可以对上面进行封装一下:
1:新增帮助类:
1 public class SiteConfig 2 { 3 private static IConfiguration _iConfiguration = null; 4 5 /// <summary> 6 /// key的值 7 /// </summary> 8 public static string AppSetting(string key) 9 { 10 string str = _iConfiguration.GetSection(key)?.Value; 11 return str; 12 } 13 14 public static void SetAppSetting(IConfiguration iConfiguration) 15 { 16 _iConfiguration = iConfiguration; 17 } 18 }
2:然后在Startup启动时初始化config对象:
1 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 2 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 3 { 4 SiteConfig.SetAppSetting(this.Configuration); //初始化config对象 5 6 app.UseSession(); 7 app.UseStaticFiles(); 8 app.UseCookiePolicy(); 9 app.UseMvc(routes => 10 { 11 routes.MapRoute( 12 name: "default", 13 template: "{controller=Home}/{action=Index}/{id?}"); 14 }); 15 }
3:直接在用到的地方可以直接拿来使用,具体使用如下:
1 var test1 = SiteConfig.AppSetting("option1"); 2 var test2 = SiteConfig.AppSetting("wizards:1:Name"); 3 var test3 = SiteConfig.AppSetting("subsection:suboption1"); 4 var test4 = SiteConfig.AppSetting("subsection:suboption1");
看完上面的代码,小伙伴肯定会问,只能通过这样的方式读取吗?wizards明明就是一个json格式,我们能直接获取这样的结构体吗?答案是肯定的,下面第二条我们来具体介绍
二:netcore读取appsettings.json的整个json节点
下面我们来封装一个方法来进行读取:
1:新增工具类
1 using Microsoft.Extensions.Configuration; 2 using Microsoft.Extensions.Configuration.Json; 3 using Microsoft.Extensions.DependencyInjection; 4 using Microsoft.Extensions.Options; 5 6 namespace Test.Core.MVC6.Models 7 { 8 public class ConfigurationTool 9 { 10 public static T GetAppSettings<T>(string key) where T : class, new() 11 { 12 IConfiguration config = new ConfigurationBuilder() 13 .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }) 14 .Build(); 15 16 T appconfig = new ServiceCollection() 17 .AddOptions() 18 .Configure<T>(config.GetSection(key)) 19 .BuildServiceProvider() 20 .GetService<IOptions<T>>() 21 .Value; 22 23 return appconfig; 24 } 25 } 26 }
2:新增对应要读取的配置的json对应的实体类,我们以wizards为例:
1 public class Wizards 2 { 3 public string Name { set; get; } 4 5 public int Age { set; get; } 6 }
3:最重要的一点儿是要设置appsettings.json属性为始终复制,这样编译会生成到对应的bin目录下面,不设置,上面第一步的配置文件会找不到该文件。
4:通过下面调用:
1 //wizards为Appsettings.json文件的节点的名字 2 var wizardLists =ConfigurationTool.GetAppSettings<List<Wizards>>("wizards");
这样就实现了读取配置文件整个格式。