【问题标题】:How to set up and work with ASP.net 5 RC1 Configurations?如何设置和使用 ASP.net 5 RC1 配置?
【发布时间】:2015-12-30 17:13:06
【问题描述】:

我对新配置系统在 ASP.net 5 中的工作方式感到非常困惑。是的,我知道我创建了一个 config.json,但是如何在我的代码中访问它的内容,尤其是在 Startup.cs 中?

许多教程使用Configuration 类,而Microsoft.Extensions.Configuration 似乎不存在。他们似乎使用Microsoft.Framework.ConfigurationModel。这不是“不再有效”吗?我认为这是因为 Intellisense 没有为我提供 1.0.0-rc1-*。

我找不到有关如何在 ASP.net 5 RC1 中使用配置的更新指南。有人请告诉我如何做到这一点。

另外,我需要一些环境变量方面的帮助,以及它们如何与新的配置框架交互(如果它们打算以某种方式交互)。我希望能够运行应用程序,可以选择将其作为开发人员运行并将其部署为发布版本。

【问题讨论】:

  • Microsoft.Framework.* 已重命名为 Microsoft.Extensions.*See this announcement。另外,我强烈建议它订阅该 repo 上的通知。

标签: configuration asp.net-core


【解决方案1】:

在 Startup.cs 中可以设置多个配置源,可以使用 appsettings.json 之类的 json 文件,可以使用环境变量,还可以使用一个叫做 usersecrets 的新东西。添加它们的顺序很重要,因为每个配置源都可以复制相同的设置。 添加配置源越晚,它获得的优先级越高。考虑我自己项目中的这个示例,还可以查看 cmets:

var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

if (env.IsEnvironment("Development"))
{
    // This reads the configuration keys from the secret store.
    // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}

// this file name is ignored by gitignore in my project
// so you can create it and use on your local dev machine
// remember last config source added wins if it has the same settings
builder.AddJsonFile("appsettings.local.overrides.json", optional: true);

 // most common use of environment variables would be in azure hosting
// since it is added last anything in env vars would trump the same setting in previous config sources
 // so no risk of messing up settings if deploying a new version to azure
builder.AddEnvironmentVariables();
Configuration = builder.Build();

然后,就存储配置设置而言,您应该使用具有属性的类,这些属性可以在启动时从配置映射并注册到 DI 服务,以便可以在需要它们的任何地方注入它们。有关详细示例,请参阅this question

更新:以下包来自我的 project.json 并且是所需/相关的包,智能感知与否这些当前有效:

"Microsoft.Extensions.Configuration": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Abstractions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.OptionsModel": "1.0.0-rc1-final",
"Microsoft.Extensions.DependencyInjection.Abstractions": "1.0.0-rc1-final",

【讨论】:

猜你喜欢
  • 2015-05-17
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-28
  • 2016-05-20
相关资源
最近更新 更多