在.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["subction: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.respon.writeasync(option1+"\r\n"+option2+ "\r\n"+suboption1+ "\r\n"+name1+ "\r\n"+age1+ "\r\n"+name2+ "\r\n"+age2)); if (env.isdevelopment()) { app.udeveloperexceptionpage(); } el { app.uhsts(); } app.uhttpsredirection(); app.umvc();}
结果:
public class mongodbhostoptions{ /// <summary> /// 连接字符串 /// </summary> public string connection { get; t; } /// <summary> /// 库 /// </summary> public string databa { get; t; } public string table { get; t; }}
在appttings.json文件中添加mongodbhost节点:
{ "logging": { "loglevel": { "default": "warning" } }, "option1": "value1_from_json", "option2": 2, "subction": { "suboption1": "subvalue1_from_json" }, "student": [ { "name": "gandalf", "age": "1000" }, { "name": "harry", "age": "17" } ], "allowedhosts": "*", //mongodb "mong湖南台跨年演唱会odbhost": { "connection": "mongodb://127.0.0.1:27017", "databa": "templatedb", "table": "cdatemplateinfo" }}
注意:
mongodbhost里面的属性名必须要和定义的实体类里面的属性名称一致。
添加optionconfigure方法绑定
private void optionconfigure(irvicecollection rvices){ //mongodbhost信息 rvices.configure<mongodbhostoptions>(configuration.getction("mongodbhost"));}
在configurervices方法中调用上面定义的方法:
public void configurervices(irvicecollection rvices){ // 调用optionconfigure方法 optionconfigure(rvices); rvices.addmvc().tcompatibilityversion(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/[cont黄文秀时代楷模roller]")] [apicontroller] public class mongodbcontroller2021八省联考 : controllerba { private readonly mongodbhostoptions _mongodbhostoptions; /// <summary> /// 通过构造函数注入 /// </summary> /// <param name="mongodbhostoptions"></param> public mongodbcontroller(ioptions<mongodbhostoptions> mongodbhostoptions) { _mongodbhostoptions = mongodbhostoptions.value; } [httpget] public async task get() { await respon.writeasync("connection:" + _mongodbhostoptions.connection + "\r\ndataba;" + _mongodbhostoptions.databa + "\r\ntable:" + _mongodbhostoptions.table); } }}
运行结果:
在上面的例子中都是读取的系统自带的appttings.json文件,那么该如何读取我们自己定义的json文件呢?这里可以使用configurationbuilder类。
var builder = new configurationbuilder();
builder.addjsonfile("path", fal, true);
其中path表示json文件的路径,包括路径和文件名。
builder.add(new jsonconfigurationsource {path= "custom.json",optional=fal,reloadonchange=true }).build()
具体代码如下:
private void customoptionconfigure(irvicecollection rvices){ iconfiguration _configuration; var builder = new configurationbuilder(); // 方式1 //_configuration = builder.addjsonfile("custom.json", fal, true).build(); // 方式2 _configuration = builder.add(new jsonconfigurationsource {path= "custom.json",optional=fal,reloadonchange=true }).build(); rvices.configure<websiteoptions>(_configuration.getction("websiteconfig"));}
configurervices方法如下:
public void configurervices(irvicecollection rvices){ // 调用optionconfigure方法 optionconfigure(rvices); customoptionconfigure(rvices); rvices.addmv政务信息范文c().tcompatibilityversion(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 : controllerba { private readonly mongodbhostoptions _mongodbhostoptions; private readonly websiteoptions _websiteoptions; /// <summary> /// 通过构造函数注入 /// </summary> /// <param name="mongodbhostoptions"></param> public mongodbcontroller(ioptions<mongodbhostoptions> mongodbhostoptions,ioptions<websiteoptions> websiteoptions) { _mongodbhostoptions = mongodbhostoptions.value; _websiteoptions = websiteoptions.value; } [httpget] public async task get() { await respon.writeasync("connection:" + _mongodbhostoptions.connection + "\r\ndataba;" + _mongodbhostoptions.databa + "\r\ntable:" + _mongodbhostoptions.table); await respon.writeasync("\r\n"); await respon.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;usi我的家乡作文800字ng system.text;namespace common{ public class jsonconfighelper { public static t getappttings<t>(string filename, string key) where t : class, new() { // 获取bin目录路径 var directory = appcontext.badirectory; 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, fal, true); configuration = builder.build(); var appconfig = new rvicecollection() .addoptions() .configure<t>(configuration.getction(key)) .buildrviceprovider() .getrvice<ioptions<t>>() .value; return appconfig; } }}
1、microsoft.extensions.configuration2、microsoft.extensions.configuration.json3、microsoft.extensions.options4、microsoft.extensions.options.configurationextensions5、microsoft.extensions.options注意:这里要添加如下几个程序集,并且要注意添加的程序集的版本要和.net core web项目里面的程序集版本一致,否则会报版本冲突的错误
json文件如下:
{ "websiteconfig": { "websitename": "customwebsite", "websiteurl": "https:localhost:12345" }, "dbconfig": { "datasource": "127.0.0.1", "initialcatalog": "mydb", "urid": "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; t; } public string initialcatalog { get; t; } public string urid { get; t; } public string password { get; t; } }}
注意:这里的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 : controllerba { private readonly mongodbhostoptions _mongodbhostoptions; private readonly websiteoptions _websiteoptions; /// <summary> /// 通过构造函数注入 /// </summary> /// <param name="mongodbhostoptions"></param> public mongodbcontroller(ioptions<mongodbhostoptions> mongodbhostoptions,ioptions<websiteoptions> websiteoptions) { _mongodbhostoptions = mongodbhostoptions.value; _websiteoptions = websiteoptions.value; } [httpget] public async task get() { dbhostoptions dboptions = jsonconfighelper.getappttings<dbhostoptions>("custom.json", "dbconfig"); await respon.writeasync("datasource:" + dboptions.datasource + "\r\ninitialcatalog;" + dboptions.initialcatalog+ "\r\nurid:"+dboptions.urid+ "\r\npassword"+dboptions.password); await respon.writeasync("\r\n"); await respon.writeasync("connection:" + _mongodbhostoptions.connection + "\r\ndataba;" + _mongodbhostoptions.databa + "\r\ntable:" + _mongodbhostoptions.table); await respon.writeasync("\r\n"); await respon.writeasync("websitename:" + _websiteoptions.websitename + "\r\nwebsiteurl;" + _websiteoptions.websiteurl); } }}
运行结果:
到此这篇关于asp.net core读取json格式配置文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。
本文发布于:2023-04-06 03:34:53,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/f2626799259520551597ecdaca2e1bc0.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:ASP.NET CORE读取json格式配置文件.doc
本文 PDF 下载地址:ASP.NET CORE读取json格式配置文件.pdf
留言与评论(共有 0 条评论) |