在空項目中是沒有配置文件的,首先要新建一個,配置文件內容如下,下麵來讀取各個內容 { "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Con ...
在空項目中是沒有配置文件的,首先要新建一個,配置文件內容如下,下麵來讀取各個內容
{ "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 讀取配置文件的方法