不确定我在这里错过了什么,但我无法从我的应用程序设置中获得值。Json在我的。net核心应用程序。我有我的appsettings。json:

{
    "AppSettings": {
        "Version": "One"
    }
}

启动:

public class Startup
{
    private IConfigurationRoot _configuration;
    public Startup(IHostingEnvironment env)
    {
        _configuration = new ConfigurationBuilder()
    }
    public void ConfigureServices(IServiceCollection services)
    {
      //Here I setup to read appsettings        
      services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
    }
}

模型:

public class AppSettings
{
    public string Version{ get; set; }
}

控制器:

public class HomeController : Controller
{
    private readonly AppSettings _mySettings;

    public HomeController(IOptions<AppSettings> settings)
    {
        //This is always null
        _mySettings = settings.Value;
    }
}

_mySettings总是空的。我是不是遗漏了什么?


当前回答

亚比谢克的回答是:

如果你想将值导入到静态类中,那么只需使用(ReSharper推荐):

static IConfiguration conf = (JsonConfigurationExtensions.AddJsonFile(new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()), "appsettings.json").Build());

private static string AuthorizationServiceURL { get; } = conf["ServiceUrls:AuthorizationUrl"];

// appsettings.json
{
  "ServiceUrls": {
    "AuthorizationUrl": "https://example.com/authorize"
  } 
}

其他回答

我认为最好的选择是:

创建一个模型类作为配置模式 在DI注册: services.Configure (Configuration.GetSection(“democonfig”)); 从控制器中的DI中获取模型对象的值: private readonly myConfig; (IOptions<your_model> configOps) { 这一点。myConfig = configOps.Value; }

只需创建一个AnyName.cs文件并粘贴以下代码。

using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace Custom
{
    static class ConfigurationManager
    {
        public static IConfiguration AppSetting { get; }
        static ConfigurationManager()
        {
            AppSetting = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("YouAppSettingFile.json")
                    .Build();
        }
    }
}

必须替换YouAppSettingFile。Json文件名与您的文件名。 您的.json文件应该如下所示。

{
    "GrandParent_Key" : {
        "Parent_Key" : {
            "Child_Key" : "value1"
        }
    },
    "Parent_Key" : {
        "Child_Key" : "value2"
    },
    "Child_Key" : "value3"
}

现在你可以使用它了。 不要忘记在你想要使用的类中添加引用。

using Custom;

检索值的代码。

string value1 = ConfigurationManager.AppSetting["GrandParent_Key:Parent_Key:Child_Key"];
string value2 = ConfigurationManager.AppSetting["Parent_Key:Child_Key"];
string value3 = ConfigurationManager.AppSetting["Child_Key"];

再加上David Liang对Core 2.0的回答——

appsettings。json文件链接到ASPNETCORE_ENVIRONMENT变量。

ASPNETCORE_ENVIRONMENT可以设置为任何值,但是框架支持三个值:Development、Staging和Production。如果没有设置ASPNETCORE_ENVIRONMENT,它将默认为Production。

对于这三个值,这些appsettings.ASPNETCORE_ENVIRONMENT。json文件支持开箱即用- appsettings.Staging。appsettings.Development.json和appsettings.Production.json

以上三个应用程序设置json文件可用于配置多个环境。

示例- appsettings.Staging.json

{
    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "MyConfig": "My Config Value for staging."
}

使用Configuration["config_var"]检索任何配置值。

public class Startup
{
    public Startup(IHostingEnvironment env, IConfiguration config)
    {
        Environment = env;
        Configuration = config;
        var myconfig = Configuration["MyConfig"];
    }

    public IConfiguration Configuration { get; }
    public IHostingEnvironment Environment { get; }
}

从Asp.net core 2.2到以上版本,你可以编写如下代码:

步骤1。创建一个AppSettings类文件。

这个文件包含一些帮助从appsettings中按键获取值的方法。json文件。如下代码所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ReadConfig.Bsl
{
  public class AppSettings
  {
      private static AppSettings _instance;
      private static readonly object ObjLocked = new object();
      private IConfiguration _configuration;

      protected AppSettings()
      {
      }

      public void SetConfiguration(IConfiguration configuration)
      {
          _configuration = configuration;
      }

      public static AppSettings Instance
      {
          get
          {
              if (null == _instance)
              {
                  lock (ObjLocked)
                  {
                      if (null == _instance)
                          _instance = new AppSettings();
                  }
              }
              return _instance;
          }
      }

      public string GetConnection(string key, string defaultValue = "")
      {
          try
          {
              return _configuration.GetConnectionString(key);
          }
          catch
          {
              return defaultValue;
          }
      }

      public T Get<T>(string key = null)
      {
          if (string.IsNullOrWhiteSpace(key))
              return _configuration.Get<T>();
          else
              return _configuration.GetSection(key).Get<T>();
      }

      public T Get<T>(string key, T defaultValue)
      {
          if (_configuration.GetSection(key) == null)
              return defaultValue;

          if (string.IsNullOrWhiteSpace(key))
              return _configuration.Get<T>();
          else
              return _configuration.GetSection(key).Get<T>();
      }

      public static T GetObject<T>(string key = null)
      {
          if (string.IsNullOrWhiteSpace(key))
              return Instance._configuration.Get<T>();
          else
          {
              var section = Instance._configuration.GetSection(key);
              return section.Get<T>();
          }
      }

      public static T GetObject<T>(string key, T defaultValue)
      {
          if (Instance._configuration.GetSection(key) == null)
              return defaultValue;

          if (string.IsNullOrWhiteSpace(key))
              return Instance._configuration.Get<T>();
          else
              return Instance._configuration.GetSection(key).Get<T>();
      }
  }
}

步骤2。AppSettings对象的初始配置

我们需要声明和加载appsettings。json文件,加载AppSettings对象的配置信息。我们将在Startup.cs文件的构造函数中完成这项工作。 请注意行AppSettings.Instance.SetConfiguration(配置);

public Startup(IHostingEnvironment evm)
{
    var builder = new ConfigurationBuilder()
      .SetBasePath(evm.ContentRootPath)
      .AddJsonFile("appsettings.json", true, true)
      .AddJsonFile($"appsettings.{evm.EnvironmentName}.json", true)
      .AddEnvironmentVariables();
    Configuration = builder.Build(); // load all file config to Configuration property 
    AppSettings.Instance.SetConfiguration(Configuration);       
}

现在我有了appsettings。Json文件与一些关键字如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ConnectionString": "Data Source=localhost;Initial Catalog=ReadConfig;Persist Security Info=True;User ID=sa;Password=12345;"
  },
  "MailConfig": {
    "Servers": {
      "MailGun": {
        "Pass": "65-1B-C9-B9-27-00",
        "Port": "587",
        "Host": "smtp.gmail.com"
      }
    },
    "Sender": {
      "Email": "example@gmail.com",
      "Pass": "123456"
    }
  }
}

步骤3。从操作中读取配置值

我在Home控制器中演示一个动作,如下所示:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        var connectionString = AppSettings.Instance.GetConnection("ConnectionString");
        var emailSender = AppSettings.Instance.Get<string>("MailConfig:Sender:Email");
        var emailHost = AppSettings.Instance.Get<string>("MailConfig:Servers:MailGun:Host");

        string returnText = " 1. Connection String \n";
        returnText += "  " +connectionString;
        returnText += "\n 2. Email info";
        returnText += "\n Sender : " + emailSender;
        returnText += "\n Host : " + emailHost;

        return Content(returnText);
    }
}

结果如下:

点击查看结果

我只是创建了一个静态类,并在Startup.cs中设置了一个配置变量

public static class GlobalConfig { 
    public static IConfiguration config { get; set; } 
}

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        GlobalConfig.config = configuration;

    }
}

然后在任何地方使用它:

var keyVal = GlobalConfig.config["key"];

似乎是访问配置文件并使其在任何地方可用的最简单的方法。