是否可以在Visual Studio中向.NET Core项目添加.settings文件?如果没有,使用.NET Core实现此目的的等效/替代方法是什么?
答案 0 :(得分:9)
您可以从appsettings
文件中将强类型值添加到IOC容器中:
{
// ...other stuff...
"MyConfiguration": {
"ValueOne": "Some value",
"ValueTwo": "2"
}
}
public class MyConfiguration
{
public string ValueOne { get; set; }
public int ValueTwo { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddOptions();
services.Configure<MyConfiguration>(Configuration.GetSection("MyConfiguration"));
}
然后您可以通过请求IOptions<MyConfiguration>
来获取它们,如下所示:
public class HomeController : Controller
{
public HomeController(IOptions<MyConfiguration> config)
{
var someValue = config.Value.ValueOne; // "Some value"
}
}