【问题标题】:.net-core authentication issue.net-core 身份验证问题
【发布时间】:2020-02-24 23:20:14
【问题描述】:

我将借助 .net-core 版本 2 对用户进行身份验证。 注册后,“SqlNullValueException:数据为 Null。无法对 Null 值调用此方法或属性。” err 会出现在 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?}");
 });
}

【问题讨论】:

  • 这可能是您在 startup.cs 中的设置或您要连接的数据库中的问题。您能否展示一下您是如何在 startup.cs 中初始化安全性的?
  • @GlennSills startup.cs 附加到帖子
  • 如果我没记错的话,那是实现 Identity Server auth 的核心 1.x 方式。在核心 2.x 中,您将身份实现为服务而不是中间件。
  • 你检查signInManager是否正确?注册为 services.AddTransient &lt; ApplicationDbContext &gt; (); 后,您的 dbcontext 是什么样的?
  • 点击账号验证后会出现这个问题。此外,如果数据库中存在用户电子邮件,则会在登录时间后发生此问题。

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


【解决方案1】:

您好像忘记初始化 ApplicationDbContext

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2019-10-31
    • 2020-03-09
    • 2018-12-17
    • 2020-10-28
    • 2020-10-15
    • 2017-06-26
    相关资源
    最近更新 更多