根据http://blog.jsinh.in/asp-net-5-configuration-microsoft-framework-configurationmodel/,情况发生了变化。但是,我无法从该文档中了解如何阅读appSettings
个密钥。有一个关于从ini文件中读取的例子。
如何避免使用旧的System.Configuration.ConfigurationManager
从web.config中读取AppSettings
个键值?
答案 0 :(得分:7)
将json
文件添加到项目根目录: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;
}
答案 1 :(得分:0)
我不确定System.ConfigurationManager.AppSettings
[MSDN]有什么问题,因为它仍适用于4.5&amp; 4.6
但我认为你要求的是System.Configuration.AppSettingsReader.GetValue()
[MSDN]
答案 2 :(得分:0)
您可以使用[&#34; setting-key&#34;]语法获取值:
IConfiguration _configuration;
...
var setting = _configuration["SomeKey"];
或者您可以将配置部分解析为某个自定义对象,如下所示:
IConfiguration configuration;
...
var myCustomObject = configuration.GetSection("SomeSection").Get<MyCustomObject>();
注意 - 在第二种方法中,您应该参考以下MS Nugget包: