不知道我在这里缺少什么,但是我没有从我appsettings.json
的.NET Core应用程序中获取值。我已经读了几乎所有关于appsettings.json
归国的文章NullReferenceException
。我知道有重复的帖子,但是他们没有解决问题
我已经完成了我所知道的设置,也可以在线阅读,但仍然返回null。我已经重构了几次代码,但仍然遇到了
NullReferenceException:对象引用未设置为对象的实例。
Startup.cs +中的ShopAPI.Startup.ConfigureServices(IServiceCollection服务)
var key = Encoding.UTF8.GetBytes(Configuration [“ ApplicationSettings:JWT_Secret”]。ToString());
System.RuntimeMethodHandle.InvokeMethod(对象目标,对象[]参数,签名sig,布尔构造函数,布尔wrapExceptions)
Startup
类:
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中的配置不同,我实际上遵循了本教程。
对于那些可能面临相同问题的人
var applicationSettings = Configuration.GetSection("AddSettings");
services.Configure<ApplicationSettings>(applicationSettings);
var appSettingsSecretKey = applicationSettings.Get<ApplicationSettings>();
然后将变量传递appSettingsSecretKey
给
var key = Encoding.ASCII.GetBytes(appSettingsSecretKey.JWT_Secret);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句