一.引用
using Microsoft.Extensions.Configuration;
二.使用接口服务:IConfiguration
注:认真观察这个类,这已经被startup.cs自动注入了,无需手动做注入操作
控制器中要使用这个接口对象,需要在构造函数中获取它
[Route("IDCardOCR")] public class IDCardOCRController : ControllerBase { public IConfiguration Configuration { get; } public IDCardOCRController(IConfiguration configuration) { Configuration = configuration; } [HttpGet("test")] public string Test() { string SecretId = Configuration.GetSection("AppConfig")["SecretId"]; string SecretKey = Configuration.GetSection("AppConfig")["SecretKey"]; return SecretId + ";" + SecretKey; } }
附注json内容结构:
读取数组结构的数据:
"mongo": [ { "GameAngVersion": "default", "connectionString": "mongodb://0.0.0.0:27017", "databaseName": "GameEditorDefault" }, { "GameAngVersion": "2021-SYY", "connectionString": "mongodb:/0.0.0.0:27017", "databaseName": "GameEditorSYY" } ]
对应的代码实体结构:
public class MongoDbSetting { /// <summary> /// 游戏ID与版本号 /// </summary> public string GameAngVersion { get; set; } /// <summary> /// 数据库连接串 /// </summary> public string ConnectionString { get; set; } /// <summary> /// 数据库名称 /// </summary> public string DatabaseName { get; set; } }
获取方式:
List<MongoDbSetting> list = config.GetSection("mongo").Get<List<MongoDbSetting>>()