一、Json配置文件
1、这里的配置文件指的是下图
2、json配置文件示例
1 2 3 4 5 6 7 8 9 10 11 12 13
| { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "Setting": { "Url": "http://localhost:8080/", "Name": "localhost" } }
|
二、读取配置文件的几种方式
1、方式一:直接读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| [ApiController] [Route("[controller]/[action]")] public class TestController: ControllerBase { public IConfiguration _configuration { get; set; } public TestController(IConfiguration configuration) { _configuration = configuration; } [HttpGet, HttpPost] public void GetConfigDemo1() { var url = _configuration["Setting:Url"]; var url2 = _configuration.GetValue<string>("Setting:Url"); var url3 = _configuration.GetSection("Setting").GetSection("Url").Value; } }
|
2、方式二:读取Json对象
1)新建应用设置类AppSettings
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
public static class AppSettings { public static SettingClass settingClass { get; set; } public static void Init(IConfiguration configuration) { settingClass = new SettingClass(); configuration.Bind("Setting", settingClass); } }
|
2)新建Json模块Setting类
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
public class SettingClass { public string Url { get; set; } public string Name { get; set; } }
|
3)在Startup.cs中调用AppSettings的初始化方法
1 2
| AppSettings.Init(Configuration);
|
4)在控制器中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| [ApiController] [Route("[controller]/[action]")] public class TestController: ControllerBase { public IConfiguration _configuration { get; set; } public TestController(IConfiguration configuration) { _configuration = configuration; } [HttpGet, HttpPost] public void GetConfigDemo2() { var url = AppSettings.settingClass.Url; var name = AppSettings.settingClass.Name; } } }
|
3、方式三:在注册服务中绑定实体类与Json文件,使用时声明为全局常量
1)在Startup.cs中将Json模块类与Json文件对应内容绑定(Json模块类如方式2的SettingClass类)
1 2 3 4 5
| services.Configure<SettingClass> (option => { option.Url = Configuration["Setting:Url"]; option.Name = Configuration["Setting:Name"]; });
|
2)在控制器中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| [ApiController] [Route("[controller]/[action]")] public class TestController: ControllerBase { public IConfiguration _configuration { get; set; } public string UrlStr { get; set; } public string NameStr { get; set; } public TestController(IConfiguration configuration, IOptions<SettingClass> settings) { _configuration = configuration; UrlStr = settings.Value.Url; NameStr = settings.Value.Name; } [HttpGet, HttpPost] public void GetConfigDemo3() { var url = UrlStr; var name = NameStr; } }
|
以上就是.net core 读取配置文件的几种方式的介绍,做此记录,如有帮助,欢迎点赞关注收藏!