在使用ASP.NET時,都是使用ConfigurationManager去存取config檔,但在ASP.NET Core改為注入的方式存取。除了讀取config檔外,還能從不同來源載入設定,最重要的是:讀進來後可以用強型別了。
我們在appsettings.json中加入一段自訂的參數
{
"MySettings": {
"Volume": 10,
"IsMute": false,
"Display": "1920*1080",
"InputMapping": {
"Up": "W",
"Down": "S",
"Left": "A",
"Right": "D"
}
}
}
存取config檔時,先在constructer中注入IConfiguration
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
之後就能取到自訂參數了,階層是以:做區分
string volume = _configuration["MySettings:Volume"];
string moveUpKey = _configuration["MySettings:InputMapping:Up"];
但這樣做的缺點是取出的值都是字串,字串以外的型別就需要再另外做轉型。
如果要用強型別的話,首先建立對應的class。
public class MySettings
{
public int Volume { get; set; }
public bool IsMute { get; set; }
public string Display { get; set; }
public InputMappingOption InputMappings { get; set; }
public class InputMappingOption
{
public string Up { get; set; }
public string Down { get; set; }
public string Left { get; set; }
public string Right { get; set; }
}
}
在Startup.cs加入強型別的自訂參數
public class Startup
{
private IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
//在容器加入強型別的自訂設定
services.Configure<MySettings>(_configuration.GetSection("MySettings"));
}
}
constructer改成注入IOptions<T>
public HomeController(IOptions<MySettings> options)
{
_mySettings = options.Value;
}
之後就能用強型別的自訂參數了,在開發上方便不少。
bool isMute = _mySettings.IsMute;
string moveDownKey = _mySettings.InputMappings.Down;
最後附上完整程式碼
參考資料: