如何使用ASP.NET Core 配置文件

前言

在ASP.NET ,我们使用XML格式的.Config文件来作为配置文件,而在ASP.NET Core,我们有了更多的选择,可以用回XML,也可以用Json、Ini文件作为配置文件

Json配置文件的使用

在创建ASP.NET Core的项目的时候,框架会自动添加appsettings.json文件和添加IConfiguration的注入。

public Startup(IConfiguration configuration)
{
 Configuration = configuration;
}

当我们在Startup构造函数添加一个IConfiguration参数,框架就会根据注入库来进行注入,除此之外还有IHostingEnvironment,如果在构造函数添加这个参数,框架也会注入对应的实现类

如果我们想要自己添加Json配置,该怎么做呢?

//SetBasePath方法用来指定配置文件的所在地,env.ContentRootPath是获取或设置包含应用程序内容文件的目录的绝对路径。
 //AddJsonFile方法是使用JsonConfigurationSource来接收Json文件,并添加到ConfigurationBuilder中的Sources中
 //Build()调用
 var config=new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
 .AddJsonFile("appsettings.json")
 .Build();
 Configuration = config;

如果不通过IHostingEnvironment来获取绝对路径,也可以使用Directory.GetCurrentDirectory()方法来获得

测试:

public IActionResult Index()
{
 var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
 .AddJsonFile("appsettings.json").Build(); 
 string value = config.GetConnectionString("MySqlConnection");
 
 string value2 = config.GetSection("Test").Value;
 
 return Content($"{value},Test:{value2}");
}
public IActionResult Index()
{
 var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
 .AddJsonFile("appsettings.json").Build(); 
 string value = config.GetConnectionString("MySqlConnection");
 
 string value2 = config.GetSection("Test").Value;
 
 return Content($"{value},Test:{value2}");
}

那复杂的键值或者数组,又该如何获得呢?

{
 "Teacher": {
 "name": "Tom",
 "age": "12",
 "Students": [
 {
 "name": "Docker",
 "age": "13"
 },
 {
 "name": "Nginx",
 "age": "45"
 }
 ]
 } 	
}

我们想要获取Teacher的name值数组Students第二个的name值,怎么获取呢?

public IActionResult Index()
{
 var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
 .AddJsonFile("appsettings.json").Build();
 string value = config.GetSection("Teacher:name").Value;
 //
 string value2 = config.GetSection("Teacher:Students:1:name").Value;
 
 return Content($"{value},Test:{value2}");
 
}

PS:从Teacher:name和Teacher:Students:1:name这两个中可以寻找规律,当然获取方式不止这一种,还可以使用Config[“Teacher:Students:1:name”]来获取

如果我们想用对象来存储配置文件的键值该如何做呢?

//appsetting.json
{
 "RedisConfig": {
 "host": "127.0.0.1",
 "MasterPort": "6379",
 "SlavePort": "6380",
 "PassWord": "wen123"
 }
}

RedisHelper类

public class RedisHelper:IRedis
{
 public string host { get; set; }
 
 public string MasterPort { get; set; }
 
 public string SlavePort { get; set; }
 
 public string PassWord { get; set; }
 
}
public IActionResult Index()
{
 var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
 .AddJsonFile("appsettings.json").Build();
 //创建一个自带的IOC容器
 var collection = new ServiceCollection();
 collection.AddOptions().Configure<RedisHelper>(config.GetSection("RedisConfig"));
 RedisHelper redishelper = collection.BuildServiceProvider().GetService<IOptions<RedisHelper>>().Value;
 
 return Content($"host:{redishelper.host},MasterPort:{redishelper.MasterPort}");
}

还有另一种写法:在Startup类的ConfigureServices方法里面,向services添加代码,通过构造函数来构造RedisHelper类

services.AddOptions().Configure<RedisHelper>(Configuration.GetSection("RedisConfig"));
private RedisHelper _redis;

public HomeController(IOptions<RedisHelper> options)
{
 _redis = options.Value;
}

public IActionResult Index()
{
 return Content($"host:{_redis.host},MasterPort:{_redis.MasterPort}");
}

XML配置文件的使用

这里简单记录一下,提取配置文件的值大致与上面做法没有太大的区别,在构造IConfiguration的时候把AddJsonFile改成AddXmlFile就行了

//XMLDemo文件
<?xml version="1.0" encoding="utf-8" ?>
<Test>
 <mysqlConnectionStrings>sdfl</mysqlConnectionStrings>
 <test>
 <connection>sdfasdf</connection>
 <connection2>sdfdsafsfs</connection2>
 </test>
 <test2>
 <test3>
 <connection>dfgfdg</connection>
 </test3>
 </test2>
</Test>
public IActionResult Index()
{
 var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
 .AddXmlFile("XMLDemo.xml").Build();
 var value = config.GetSection("mysqlConnectionStrings").Value;
 var value2 = config.GetSection("test:connection2").Value;

 return Content($"value:{value},value2:{value2}");

作者:我赢了算我输原文地址:https://blog.csdn.net/MDZZ666/article/details/96282039

%s 个评论

要回复文章请先登录注册