一,appsettings.json配置添加如下
"MyOptions": { "Id": 2, "Name": "appsettings" }
二,使用IConfiguration读取配置,如下控制器代码
namespace TestCore.Controllers { [ApiController] [Route("[controller]/[action]")] public class ConfigTestController : ControllerBase { private IConfiguration _configuration; public ConfigTestController( IConfiguration configuration) { _configuration = configuration; } public string GetConfiguration() { return "-configuration获取:" + _configuration.GetSection("MyOptions").GetValue<string>("Name"); } } }
ps:测试代码没有更改Program默认配置文件所以默认读的是appsettings.json配置文件
二,IOptions的使用
namespace TestCore.Controllers { [ApiController] [Route("[controller]/[action]")] public class ConfigTestController : ControllerBase { private TestModel _options; public ConfigTestController(IOptions<TestModel> options) { _options = options.Value; } public string GetIOptions() { return "IOptions获取:" + _options.Name; } } }
Startup的ConfigureServices有两种写法,第一是读取配置文件,第二是自己给实体赋值
public void ConfigureServices(IServiceCollection services) { services.Configure<TestModel>(Configuration.GetSection("MyOptions")); //获取默认配置文件的值 //services.Configure<TestModel>(m=> { m.Name = "startup读取";m.Id = 1; }); //获取自己实例的配置 services.AddControllers(); }
综上所有配置的使用方法