一、自定义读取配置文件信息appsettings.json
1.在startup类配置
1 public iconfiguration configuration { get; } 2 public iwebhostenvironment env { get; } 3 public startup(iconfiguration configuration, iwebhostenvironment env) 4 { 5 configuration = configuration; 6 env = env; 7 }
2.在startup类的configureservices配置
services.addsingleton(new appsettings(env.contentrootpath));
3.新建一个appsettings操作类
static iconfiguration configuration { get; set; } static string contentpath { get; set; } public appsettings(string contentpath) { string path = "appsettings.json"; configuration = new configurationbuilder() .setbasepath(contentpath) .add(new jsonconfigurationsource { path = path, optional = false, reloadonchange = true }) .build(); } /// <summary> /// 封装要操作的字符 /// </summary> /// <param name="sections">节点配置</param> /// <returns></returns> public static string get(params string[] sections) { try { if (sections.any()) { return configuration[string.join(":", sections)]; } } catch (exception) { } return ""; }
4.如何使用
string test = appsettings.get(new string[] { "test", "test1" });
黄山市民网:https://www.huangshanshimin.com/