在.net framework中,配置文件一般采用的是xml格式的,.net framework提供了专门的configurationmanager来读取配置文件的内容,.net core中推荐使用json格式的配置文件,那么在.net core中该如何读取json文件呢?
看下面的代码:
public iconfiguration configuration { get; }
configuration属性就是.net core中提供的用来读取json文件。例如:
public void configure(iapplicationbuilder app, ihostingenvironment env) { string option1 = $"option1 = {this.configuration["option1"]}"; string option2 = $"option2 = {this.configuration["option2"]}"; string suboption1 = $"suboption1 = {this.configuration["subsection:suboption1"]}"; // 读取数组 string name1 = $"name={this.configuration["student:0:name"]} "; string age1 = $"age= {this.configuration["student:0:age"]}"; string name2 = $"name={this.configuration["student:1:name"]}"; string age2 = $"age= {this.configuration["student:1:age"]}"; // 输出 app.run(c => c.response.writeasync(option1+"\r\n"+option2+ "\r\n"+suboption1+ "\r\n"+name1+ "\r\n"+age1+ "\r\n"+name2+ "\r\n"+age2)); if (env.isdevelopment()) { app.usedeveloperexceptionpage(); } else { app.usehsts(); } app.usehttpsredirection(); app.usemvc(); }
结果:
public class mongodbhostoptions { ////// 连接字符串 ///public string connection { get; set; } ////// 库 ///public string database { get; set; } public string table { get; set; } }
在appsettings.json文件中添加mongodbhost节点:
{ "logging": { "loglevel": { "default": "warning" } }, "option1": "value1_from_json", "option2": 2, "subsection": { "suboption1": "subvalue1_from_json" }, "student": [ { "name": "gandalf", "age": "1000" }, { "name": "harry", "age": "17" } ], "allowedhosts": "*", //mongodb "mongodbhost": { "connection": "mongodb://127.0.0.1:27017", "database": "templatedb", "table": "cdatemplateinfo" } }
注意:
mongodbhost里面的属性名必须要和定义的实体类里面的属性名称一致。
添加optionconfigure方法绑定
private void optionconfigure(iservicecollection services) { //mongodbhost信息 services.configure(configuration.getsection("mongodbhost")); }
在configureservices方法中调用上面定义的方法:
public void configureservices(iservicecollection services) { // 调用optionconfigure方法 optionconfigure(services); services.addmvc().setcompatibilityversion(compatibilityversion.version_2_1); }
在控制器中使用,代码如下:
using system; using system.collections.generic; using system.linq; using system.threading.tasks; using microsoft.aspnetcore.http; using microsoft.aspnetcore.mvc; using microsoft.extensions.options; namespace readjsondemo.controllers { [route("api/[controller]")] [apicontroller] public class mongodbcontroller : controllerbase { private readonly mongodbhostoptions _mongodbhostoptions; ////// 通过构造函数注入 //////public mongodbcontroller(ioptionsmongodbhostoptions) { _mongodbhostoptions = mongodbhostoptions.value; } [httpget] public async task get() { await response.writeasync("connection:" + _mongodbhostoptions.connection + "\r\ndatabase;" + _mongodbhostoptions.database + "\r\ntable:" + _mongodbhostoptions.table); } } }
运行结果:
在上面的例子中都是读取的系统自带的appsettings.json文件,那么该如何读取我们自己定义的json文件呢?这里可以使用configurationbuilder类。
var builder = new configurationbuilder();
builder.addjsonfile("path", false, true);
其中path表示json文件的路径,包括路径和文件名。
builder.add(new jsonconfigurationsource {path= "custom.json",optional=false,reloadonchange=true }).build()
具体代码如下:
private void customoptionconfigure(iservicecollection services) { iconfiguration _configuration; var builder = new configurationbuilder(); // 方式1 //_configuration = builder.addjsonfile("custom.json", false, true).build(); // 方式2 _configuration = builder.add(new jsonconfigurationsource {path= "custom.json",optional=false,reloadonchange=true }).build(); services.configure(_configuration.getsection("websiteconfig")); }
configureservices方法如下:
public void configureservices(iservicecollection services) { // 调用optionconfigure方法 optionconfigure(services); customoptionconfigure(services); services.addmvc().setcompatibilityversion(compatibilityversion.version_2_1); }
控制器代码如下:
using system; using system.collections.generic; using system.linq; using system.threading.tasks; using microsoft.aspnetcore.http; using microsoft.aspnetcore.mvc; using microsoft.extensions.options; namespace readjsondemo.controllers { [route("api/[controller]")] [apicontroller] public class mongodbcontroller : controllerbase { private readonly mongodbhostoptions _mongodbhostoptions; private readonly websiteoptions _websiteoptions; ////// 通过构造函数注入 //////public mongodbcontroller(ioptionsmongodbhostoptions,ioptionswebsiteoptions) { _mongodbhostoptions = mongodbhostoptions.value; _websiteoptions = websiteoptions.value; } [httpget] public async task get() { await response.writeasync("connection:" + _mongodbhostoptions.connection + "\r\ndatabase;" + _mongodbhostoptions.database + "\r\ntable:" + _mongodbhostoptions.table); await response.writeasync("\r\n"); await response.writeasync("websitename:" + _websiteoptions.websitename + "\r\nwebsiteurl;" + _websiteoptions.websiteurl); } } }
在上面的示例中都是直接在应用程序中读取的,那么如何在单独的类库中读取json文件呢?看下面的示例代码:
using microsoft.extensions.configuration; using microsoft.extensions.dependencyinjection; using microsoft.extensions.options; using system; using system.collections.generic; using system.io; using system.text; namespace common { public class jsonconfighelper { public static t getappsettings(string filename, string key) where t : class, new() { // 获取bin目录路径 var directory = appcontext.basedirectory; directory = directory.replace("\\", "/"); var filepath = $"{directory}/{filename}"; if (!file.exists(filepath)) { var length = directory.indexof("/bin"); filepath = $"{directory.substring(0, length)}/{filename}"; } iconfiguration configuration; var builder = new configurationbuilder(); builder.addjsonfile(filepath, false, true); configuration = builder.build(); var appconfig = new servicecollection() .addoptions() .configure(configuration.getsection(key)) .buildserviceprovider() .getservice() .value; return appconfig; } } }
注意:这里要添加如下几个程序集,并且要注意添加的程序集的版本要和.net core web项目里面的程序集版本一致,否则会报版本冲突的错误
json文件如下:
{ "websiteconfig": { "websitename": "customwebsite", "websiteurl": "https:localhost:12345" }, "dbconfig": { "datasource": "127.0.0.1", "initialcatalog": "mydb", "userid": "sa", "password": "123456" } }
dbhostoptions实体类定义如下:
using system; using system.collections.generic; using system.linq; using system.threading.tasks; namespace readjsondemo { public class dbhostoptions { public string datasource { get; set; } public string initialcatalog { get; set; } public string userid { get; set; } public string password { get; set; } } }
注意:这里的dbhostoptions实体类应该建在单独的类库中,这里为了演示方便直接建在应用程序中了。
在控制器中调用:
using system; using system.collections.generic; using system.linq; using system.threading.tasks; using common; using microsoft.aspnetcore.http; using microsoft.aspnetcore.mvc; using microsoft.extensions.options; namespace readjsondemo.controllers { [route("api/[controller]")] [apicontroller] public class mongodbcontroller : controllerbase { private readonly mongodbhostoptions _mongodbhostoptions; private readonly websiteoptions _websiteoptions; ////// 通过构造函数注入 //////public mongodbcontroller(ioptionsmongodbhostoptions,ioptionswebsiteoptions) { _mongodbhostoptions = mongodbhostoptions.value; _websiteoptions = websiteoptions.value; } [httpget] public async task get() { dbhostoptions dboptions = jsonconfighelper.getappsettings("custom.json", "dbconfig"); await response.writeasync("datasource:" + dboptions.datasource + "\r\ninitialcatalog;" + dboptions.initialcatalog+ "\r\nuserid:"+dboptions.userid+ "\r\npassword"+dboptions.password); await response.writeasync("\r\n"); await response.writeasync("connection:" + _mongodbhostoptions.connection + "\r\ndatabase;" + _mongodbhostoptions.database + "\r\ntable:" + _mongodbhostoptions.table); await response.writeasync("\r\n"); await response.writeasync("websitename:" + _websiteoptions.websitename + "\r\nwebsiteurl;" + _websiteoptions.websiteurl); } } }
运行结果:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。