如何阅读appSettings键

Old*_*zer 7 c# asp.net-core-mvc asp.net-core

根据http://blog.jsinh.in/asp-net-5-configuration-microsoft-framework-configurationmodel/,事情发生了变化.但是,我无法从该文档中了解如何读取appSettings密钥.虽然有一个从ini文件读取的例子.

如何避免使用旧的System.Configuration.ConfigurationManager来读取AppSettingsweb.config中的键值?

Cri*_*ufu 7

json文件添加到项目根目录:config.json

{
   "AppSettings": {
       "TestKey" :  "TestValue"
    }
}
Run Code Online (Sandbox Code Playgroud)

class为配置反序列化创建一个新的:

public class AppSettings
{
     public string TestKey { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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"));
}
Run Code Online (Sandbox Code Playgroud)

获取您的选项controller:

public HomeController(IOptions<AppSettings> settings)
{
    var value = settings.Value.TestKey;
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*Bry 1

我不确定System.ConfigurationManager.AppSettings[MSDN]有什么问题,因为它在 4.5 和 4.6 中仍然有效

但我认为你要求的是System.Configuration.AppSettingsReader.GetValue() [MSDN]