.Net core 的配置文件,不再是配置在web.config 中,而是单独的json 配置文件,解析方法:只要和合法的Json格式,怎么写随意,怎么写就怎么解析
解析方法:
1、 首先Nuget安装:Microsoft.Extensions.Configuration和Microsoft.Extensions.Configuration.Json
2、 然后using Microsoft.Extensions.Configuration;
配置文件1:appsettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
配置文件2:appjson.json
{
"db": {
"type": {
"sqlserver": {
"name": "sqlserver",
"connectionString": "server=.;database=sales;uid=sa;pwd=123456;"
},
"mysql": {
"name": "mysql",
"connectionString": "server=.;database=sales;uid=root;pwd=root;"
}
}
}
}
读取以上两个配置文件中的节点值
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace NetCoreApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
//获取配置文件(json)的目录
string currentJsonPath = Directory.GetCurrentDirectory();
//设置配置文件所在的路径
var builder = new ConfigurationBuilder().SetBasePath(currentJsonPath);
builder.AddJsonFile("appsettings.json"); //将你的配置文件加入到builder中(添加一个json文件,即我要解析这个json文件)
builder.AddJsonFile("appjson.json");//也可以添加多个配置文件
var configRoot= builder.Build();
//读取appsettings.json配置文件下的节点值
var includeScopesValue = configRoot.GetSection("Logging").GetSection("IncludeScopes").Value;
var logLevelValue= configRoot.GetSection("Logging").GetSection("LogLevel").GetSection("Default").Value;
//读取appjson.json配置文件下的节点值
var sqlserverValue = configRoot.GetSection("db").GetSection("type").GetSection("sqlserver").GetSection("connectionString").Value;
return Ok();
}
}
}