.net core 学习 读取配置文件

在空项目中是没有配置文件的,首先要新建一个,配置文件内容如下,下面来读取各个内容

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true",
  },
  "Name": "张三",
  "Person": {
    "Name": "张三",
    "Age": 18
  },
  "Persons": [
    {
      "Name": "张三",
      "Age": 18
    },
    {
      "Name": "李四",
      "Age": 18
    }
  ]
}

有时会出现中文读取乱码,用计事本打开,然后另存为 utf-8 就可以了

ConfigurationBuilder configurationBuilder =new ConfigurationBuilder();
//配置文件路径
configurationBuilder.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
var configuration = configurationBuilder.Build();
            
//读取连接字符串
var value1= configuration.GetConnectionString("DefaultConnection");

//读取自定义内容
var value2 = configuration.GetValue<string>("Name");
var value3 = configuration.GetValue<string>("Person:Name");
var value4 = configuration.GetValue<int>("Person:Age");
var value5 = configuration.GetValue<string>("Persons:0:Name");
var value6 = configuration.GetValue<int>("Persons:0:Age");

索引不是中括号感觉有点不适应

上面是读取基础值,其实还可以将 Person 和 Persons 读取为对象,不过写法要改下,首先再 Startup 类中添加一个构造函数和字段

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

public IConfiguration Configuration;

然后在 ConfigureServices 方法添加如下

services.Configure<Person>(Configuration.GetSection("Person"));
services.Configure<List<Person>>(Configuration.GetSection("Persons"));

之后是控制器中

private Person person;
private List<Person> persons;
public ConfigurationController(IOptions<Person> _person, IOptions<List<Person>> _persons)
{
    person = _person.Value;
    persons = _persons.Value;
}

以上就是 asp.net core 读取配置文件的方法

.net core 学习 读取配置文件

全文结束