[英]How to read an appSettings key
根据http://blog.jsinh.in/asp-net-5-configuration-microsoft-framework-configurationmodel/ ,事情发生了变化。 但是,我无法从该文档中了解如何阅读appSettings
键。 虽然有一个从ini文件读取的例子。
如何避免使用旧的System.Configuration.ConfigurationManager
从web.config读取AppSettings
键值?
将json
文件添加到项目根目录dir: config.json
{
"AppSettings": {
"TestKey" : "TestValue"
}
}
为配置反序列化创建一个新class
:
public class AppSettings
{
public string TestKey { get; set; }
}
在Startup.cs
:
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddMvc();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
获取controller
的选项:
public HomeController(IOptions<AppSettings> settings)
{
var value = settings.Value.TestKey;
}
您可以使用[“setting-key”]语法获取值:
IConfiguration _configuration;
...
var setting = _configuration["SomeKey"];
或者您可以将配置部分解析为某个自定义对象,如下所示:
IConfiguration configuration;
...
var myCustomObject = configuration.GetSection("SomeSection").Get<MyCustomObject>();
注意 - 在第二种方法中,您应该参考以下MS Nugget包:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.