在 MVC Core 中访问 appsetting 的最简单方法

Easiest way to access appsetting in MVC Core

appsettings.json 的 ASP.NET 核心网络应用程序中,我们有

"V9": {
"MainApp": {
  "Version": "9.07.32",

如何从 class 访问 Version?我想做类似

的事情
string version = Configuration["V9:MainApp:Version"]

但我得到 The name 'Configuration' does not exist in the current context,但没有建议使用 using 语句。我尝试使用 ConfigurationManagerConfigurationManagerdnx-core

中不可用

如果你在启动时做过

public Startup(IApplicationEnvironment appEnv, IHostingEnvironment env) {

       _config = new ConfigurationBuilder()
                .AddJsonFile("config.json")
                .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables()
            .Build();

并在 ConfigureServices

 public void ConfigureServices(IServiceCollection services) {

      services.AddSingleton(_ => _config);

你可以在需要配置的地方注入

 public SomeControllerOrService(IConfiguration conf, ...

并做

conf.Get<string>("V9:MainApp:Version");

或者您可能希望遵循选项模型模式...

更多文档 hereherehere