.NET CORE的配置文件只能用xml格式吗
在.net framework中,配置文件一般采用的是xml格式的,.net framework提供了专门的configurationmanager来读取配置文件的内容,.net core中推荐使用json格式的配置文件,那么在.net core中该如何读取json文件呢?
一、在startup类中读取json配置文件
1、使用configuration直接读取
看下面的代码:
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();
}
结果:
2、使用ioptions接口
1、定义实体类
public class mongodbhostoptions
{
////// 连接字符串
///public string connection {
get;
set;
}
////// 库
///public string database {
get;
set;
}
public string table {
get;
set;
}
}
2、修改json文件
在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里面的属性名必须要和定义的实体类里面的属性名称一致。
3、在startup类里面配置
添加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);
}
}
}
运行结果:
3、读取自定义json文件
在上面的例子中都是读取的系统自带的appsettings.json文件,那么该如何读取我们自己定义的json文件呢?这里可以使用configurationbuilder类。
实例化类
var builder = new configurationbuilder();
添加方式1
builder.addjsonfile("path", false, true);
其中path表示json文件的路径,包括路径和文件名。
添加方式2
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文件
在上面的示例中都是直接在应用程序中读取的,那么如何在单独的类库中读取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项目里面的程序集版本一致,否则会报版本冲突的错误
- 1、microsoft.extensions.configuration
- 2、microsoft.extensions.configuration.json
- 3、microsoft.extensions.options
- 4、microsoft.extensions.options.configurationextensions
- 5、microsoft.extensions.options
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);
}
}
}
运行结果:
以上就是关于“.NETCORE的配置文件只能用xml格式吗,json格式才是推荐的方法”的相关知识,感谢各位的阅读,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注网络,小编每天都会为大家更新不同的知识。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: .NET CORE的配置文件只能用xml格式吗
本文地址: https://pptw.com/jishu/654295.html
