将.settings添加到.NET Core项目中

时间:2016-10-06 21:40:43

标签: c# .net visual-studio asp.net-core settings.settings

是否可以在Visual Studio中向.NET Core项目添加.settings文件?如果没有,使用.NET Core实现此目的的等效/替代方法是什么?

1 个答案:

答案 0 :(得分:9)

您可以从appsettings文件中将强类型值添加到IOC容器中:

appsettings.json

{
  // ...other stuff...
  "MyConfiguration": {
    "ValueOne": "Some value",
    "ValueTwo": "2"
  }
}

MyConfiguration.cs

public class MyConfiguration
{
    public string ValueOne { get; set; }

    public int ValueTwo { get; set; }
}

Startup.cs

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"
    }
}