【问题标题】:Getting value from appSettings.json?从 appSettings.json 获取价值?
【发布时间】:2017-08-15 20:06:30
【问题描述】:

我无法检索 appsettings.json 中设置的值,当我运行下面的代码时,我收到错误 System.NullReferenceException: 'Object reference not set to an instance of an object.'

我做错了什么?

public static IConfigurationRoot Configuration { get; } 
....
string facebookApiId = Configuration.GetValue<string>("Authentication:Facebook:AppId");

appSettings.json

"Authentication": {
  "Facebook": {
    "IsEnabled": "false",
    "AppId": "somevalue1",
    "AppSecret": "somevalue2"
  },
  "Google": {
    "IsEnabled": "false",
    "ClientId": "somevalue3",
    "ClientSecret": "somevalue4"
  }

Startup.cs

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

【问题讨论】:

  • 你有没有用配置生成器的结果设置Configuration?发布您的 Startup 构造函数
  • 您只是没有分配您的Configuration 属性,或者在您试图获得价值之前分配它。
  • @Tseng 发布了 startup.cs
  • 您从哪里访问它?因为它是静态的,所以它可能无处不在。无论如何,配置应该可以在启动之外访问(推荐是私有的或受保护的)。静态承担在初始化之前被调用的风险。将其更改为受保护的,然后查看是否出现任何编译错误
  • 您的代码示例相互矛盾。首先是static IConfigurationRoot Configuration ,其次是IConfigurationRoot Configuration(非静态)。

标签: c# .net asp.net-core asp.net-core-mvc .net-core


【解决方案1】:

在您的代码中,您实际上有 2(两个)Configuration 属性,一个在 Startup,这很好,因为它被填充并存储在 instance 字段中,一个在未命名的控制器中,即static,似乎从未实例化。

根据MSDN article about the configuration,向控制器提供选项的推荐方法是实现基本选项和配置对象逻辑,如下所示:

// option mapping classes
public class FacebookOptions
{
    // maybe string here
    public bool IsEnabled { get; set; }
    public string AppId { get; set; }
    public string AppSecret { get; set; }
}

public class GoogleOptions
{
    // maybe string here
    public bool IsEnabled { get; set; }
    public string ClientId { get; set; }
    public string ClientSecret { get; set; }
}

// load configuration
public Startup(IHostingEnvironment env)
{
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);

    Configuration = builder.Build();
}

// map the configuration to object
public void ConfigureServices(IServiceCollection services)
{
    // Adds services required for using options.
    services.AddOptions();

    // Register the IConfiguration instance which options binds against.
    services.Configure<FacebookOptions>(Configuration.GetSection("Facebook"));
    services.Configure<GoogleOptions>(Configuration.GetSection("Google"));

    // Add framework services.
    services.AddMvc();
}

现在您可以通过依赖注入轻松获取控制器上的选项:

public class GoogleController : Controller
{
    private readonly GoogleOptions _googleOptions;

    public GoogleController(IOptions<GoogleOptions> googleOptionsAccessor)
    {
        _googleOptions = googleOptionsAccessor.Value;
    }
}

如果您需要一个完整的配置,您可以添加一些包含所有选项的通用类并使用同一篇文章中的object graph mapping

public class Authentication
{
    public FacebookOptions Google { get; set; }
    public GoogleOptions Google { get; set; }
}

// load configuration
public Startup(IHostingEnvironment env)
{
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);

    Configuration = builder.Build();

    var options = new Authentication();
    config.GetSection("Authentication").Bind(options);
}

编辑:确保您的类和配置部分的名称相同,因为这很重要,事实证明。

【讨论】:

  • 在homecontroller方法中使用时会返回null? “字符串 gClientId = _googleOptions.ClientId” ??它应该返回“somevalue3”
  • 我没有这样的问题。您确定 JSON 文件存在并且已正确填充吗? Configuration.GetSection 收到了吗?
  • 首先我在 appsettings.json 文件中添加了 Google 凭据,接下来我通过 startup.cs 在 configuratureservices 中注册了该服务。在控制器中并添加了如上所示的 google 选项,然后我在这样的语句中使用它 string googleClientId = _googleOptions.ClientId, null is returned。
  • 您是否在Startup 中找到了Google 部分?读对了吗?
  • 我修好了!,通过 appsettings.json 将“Google”重命名为 GoogleOptions 以匹配类模型并且它可以工作。
猜你喜欢
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 2020-06-11
  • 2017-01-08
相关资源
最近更新 更多