【发布时间】: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