从 appsettings.json 获取返回 NullReferenceException 的值:对象引用未设置到对象的实例。在 .net 核心 3 中
Getting value from appsettings.json returning NullReferenceException: Object reference not set to an instance of an object. in .net core 3
不确定我在这里遗漏了什么,但我没有从我的 .NET Core 应用程序中的 appsettings.json
获取值。我已经阅读了几乎所有关于 appsettings.json
返回 NullReferenceException
的内容。 我知道有重复的post,但他们都没有解决问题
我知道的设置都做了,网上也看了,但还是返回null。我已经多次重构我的代码,但仍然 运行 到
NullReferenceException: Object reference not set to an instance of an object.
ShopAPI.Startup.ConfigureServices(IServiceCollection services) in Startup.cs+
var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings : JWT_Secret"].ToString());
System.RuntimeMethodHandle.InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions)
Startup
class:
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//.Get<Dictionary<string, string>>()
services.AddOptions();
var applicationSettings = Configuration.GetSection("AppSetting");
services.Configure<ApplicationSettings>(applicationSettings);
//services.AddSingleton(Configuration.GetSection("AppSettings").Get<ApplicationSettings>());
services.AddControllers();
services.AddDbContext<ShopDbContext>(option =>
option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser,IdentityRole>()
.AddEntityFrameworkStores<ShopDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options => {
options.Password.RequireDigit = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 6;
});
services.AddCors();
//Jwt Authentication configuration
//var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings: JWT_Secret"].ToString());
var key = Encoding.UTF8.GetBytes(Configuration["AppSetting : JWT_Secret"].ToString());
services.AddAuthentication(x => {
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = false;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
};
});
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=api2;Trusted_Connection=True;Connection Timeout=120;MultipleActiveResultSets=true"
},
"AppSetting": {
"JWT_Secret": "1234567890123456",
"Client_URL": "http://localhost:4500"
},
"AllowedHosts": "*"
}
我终于修正了这个错误。我认为 .net core 3 中的配置不同
我实际上遵循了这个tutorial。
对于那些可能面临同样问题的人
var applicationSettings = Configuration.GetSection("AddSettings");
services.Configure<ApplicationSettings>(applicationSettings);
var appSettingsSecretKey = applicationSettings.Get<ApplicationSettings>();
然后将变量appSettingsSecretKey
传给
var key = Encoding.ASCII.GetBytes(appSettingsSecretKey.JWT_Secret);
不确定我在这里遗漏了什么,但我没有从我的 .NET Core 应用程序中的 appsettings.json
获取值。我已经阅读了几乎所有关于 appsettings.json
返回 NullReferenceException
的内容。 我知道有重复的post,但他们都没有解决问题
我知道的设置都做了,网上也看了,但还是返回null。我已经多次重构我的代码,但仍然 运行 到
NullReferenceException: Object reference not set to an instance of an object.
ShopAPI.Startup.ConfigureServices(IServiceCollection services) in Startup.cs+
var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings : JWT_Secret"].ToString());
System.RuntimeMethodHandle.InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions)
Startup
class:
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//.Get<Dictionary<string, string>>()
services.AddOptions();
var applicationSettings = Configuration.GetSection("AppSetting");
services.Configure<ApplicationSettings>(applicationSettings);
//services.AddSingleton(Configuration.GetSection("AppSettings").Get<ApplicationSettings>());
services.AddControllers();
services.AddDbContext<ShopDbContext>(option =>
option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser,IdentityRole>()
.AddEntityFrameworkStores<ShopDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options => {
options.Password.RequireDigit = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 6;
});
services.AddCors();
//Jwt Authentication configuration
//var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings: JWT_Secret"].ToString());
var key = Encoding.UTF8.GetBytes(Configuration["AppSetting : JWT_Secret"].ToString());
services.AddAuthentication(x => {
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = false;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
};
});
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=api2;Trusted_Connection=True;Connection Timeout=120;MultipleActiveResultSets=true"
},
"AppSetting": {
"JWT_Secret": "1234567890123456",
"Client_URL": "http://localhost:4500"
},
"AllowedHosts": "*"
}
我终于修正了这个错误。我认为 .net core 3 中的配置不同 我实际上遵循了这个tutorial。
对于那些可能面临同样问题的人
var applicationSettings = Configuration.GetSection("AddSettings");
services.Configure<ApplicationSettings>(applicationSettings);
var appSettingsSecretKey = applicationSettings.Get<ApplicationSettings>();
然后将变量appSettingsSecretKey
传给
var key = Encoding.ASCII.GetBytes(appSettingsSecretKey.JWT_Secret);