.net核心身份验证问题

时间:2019-10-29 16:58:42

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

我将在.net-core版本2的帮助下对用户进行身份验证。 注册后,“ SqlNullValueException:数据为Null。无法对Null值调用此方法或属性。”错误将出现在signInManager方法上。

我已经检查了模型和数据库中的可空数据和必需数据。

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task < IActionResult > Login(LoginViewModel model, string returnUrl = null) {
  ViewData["ReturnUrl"] = returnUrl;
  if (ModelState.IsValid) {
   var result = await signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);

   var user = new ApplicationUser {
    Email = model.Email
   };

   // ...

startup.cs文件

IConfigurationRoot configurationRoot;
public Startup(IHostingEnvironment env) {
 configurationRoot = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
  .AddJsonFile("appsettings.json").Build();
}

public void ConfigureServices(IServiceCollection services) {
 services.AddIdentity < ApplicationUser, IdentityRole > ()
  .AddEntityFrameworkStores < ApplicationDbContext > ()
  .AddDefaultTokenProviders();

 services.AddTransient < ApplicationDbContext > ();
 services.AddTransient < IEmailSender, AuthMessageServices > ();
 services.AddAuthentication();
 services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
 if (env.IsDevelopment()) {
  app.UseDeveloperExceptionPage();
  app.UseBrowserLink();
 } else {
  app.UseExceptionHandler("/Error");
 }

 app.UseAuthentication();
 app.UseStaticFiles();

 app.UseMvc(routes => {
  routes.MapRoute(
   name: "default",
   template: "{controller=Home}/{action=Index}/{id?}");
 });
}

1 个答案:

答案 0 :(得分:0)

您似乎忘记了初始化ApplicationDbContext

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));