繁体   English   中英

如何阅读appSettings键

[英]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;
}

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

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

您可以使用[“setting-key”]语法获取值:

IConfiguration _configuration;
...
var setting = _configuration["SomeKey"];

或者您可以将配置部分解析为某个自定义对象,如下所示:

IConfiguration configuration;
...
var myCustomObject = configuration.GetSection("SomeSection").Get<MyCustomObject>();

注意 - 在第二种方法中,您应该参考以下MS Nugget包:

  1. Microsoft.Extensions.Configuration
  2. Microsoft.Extensions.Configuration.Builder
  3. Microsoft.Extensions.Configuration.Json

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM