根据http://blog.jsinh.in/asp-net-5-configuration-microsoft-framework-configurationmodel/,事情发生了变化.但是,我无法从该文档中了解如何读取appSettings
密钥.虽然有一个从ini文件读取的例子.
如何避免使用旧的System.Configuration.ConfigurationManager
来读取AppSettings
web.config中的键值?
将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(Configuration.GetSection("AppSettings")); }
获取您的选项controller
:
public HomeController(IOptionssettings) { var value = settings.Value.TestKey; }