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

前言

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

Json配置文件的使用

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

1
2
3
4
public Startup(IConfiguration configuration)
{
       Configuration = configuration;
}

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

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

1
2
3
4
5
6
7
//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()方法来获得

测试:

1
2
3
4
5
6
7
8
9
10
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}");
}
1
2
3
4
5
6
7
8
9
10
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}");
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
    "Teacher": {
    "name": "Tom",
    "age": "12",
    "Students": [
      {
        "name": "Docker",
        "age": "13"
      },
      {
        "name": "Nginx",
        "age": "45"
      }
    ]
  }    
}

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

1
2
3
4
5
6
7
8
9
10
11
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”]来获取

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

1
2
3
4
5
6
7
8
9
//appsetting.json
{
   "RedisConfig": {
    "host": "127.0.0.1",
    "MasterPort": "6379",
    "SlavePort": "6380",
    "PassWord": "wen123"
   }
}

RedisHelper类

1
2
3
4
5
6
7
8
9
10
11
public class RedisHelper:IRedis
{
   public string host { get; set; }
    
   public string MasterPort { get; set; }
    
   public string SlavePort { get; set; }
    
   public string PassWord { get; set; }
    
}
1
2
3
4
5
6
7
8
9
10
11
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>>().Value;
     
    return Content($"host:{redishelper.host},MasterPort:{redishelper.MasterPort}");
}</ioptions></redishelper>

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

1
services.AddOptions().Configure<redishelper>(Configuration.GetSection("RedisConfig"));</redishelper>
1
2
3
4
5
6
7
8
9
10
11
private RedisHelper _redis;
 
public HomeController(IOptions<redishelper> options)
{
       _redis = options.Value;
}
 
public IActionResult Index()
{
     return Content($"host:{_redis.host},MasterPort:{_redis.MasterPort}");
}</redishelper>

XML配置文件的使用

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

1
2
//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>
1
2
3
4
5
6
7
8
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}");

到此这篇关于如何使用ASP.NET Core 配置文件的文章就介绍到这了,更多相关ASP.NET Core 配置文件内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/asp-net/1228.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部