.NET 7.0 API中IdentityDbContext调用UserManager触发空值异常
问题描述
基于.NET 7.0搭建API,使用EF Core搭配IdentityDbContext。在登录接口调用userManager.FindByNameAsync查找用户时触发空值异常,异常信息如下:
System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values. at Microsoft.Data.SqlClient.SqlDataReader.GetFieldValueFromSqlBufferInternal[T](SqlBuffer data, _SqlMetaData metaData, Boolean isAsync) at Microsoft.Data.SqlClient.SqlDataReader.GetFieldValueInternal[T](Int32 i, Boolean isAsync) at Microsoft.Data.SqlClient.SqlDataReader.GetFieldValue[T](Int32 i)
登录接口代码:
[HttpPost] [Route("login")] [AllowAnonymous] public async Task<IActionResult> Login([FromBody] LoginModel model) { var user = await userManager.FindByNameAsync(model.UserName); if (user != null && await userManager.CheckPasswordAsync(user, model.Password)) { var userRoles = await userManager.GetRolesAsync(user); var authClaims = new List<Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; foreach (var userRole in userRoles) { authClaims.Add(new Claim(ClaimTypes.Role, userRole)); } var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"])); var token = new JwtSecurityToken( issuer: _configuration["JWT:ValidIssuer"], audience: _configuration["JWT:ValidAudience"], expires: DateTime.Now.AddHours(3), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }); } return Unauthorized(); }
解决方案
这个异常是因为数据库中用户表的某个必填字段存了NULL值,EF Core读取时,对应实体的属性是非可空类型(比如string而非string?),导致无法将NULL映射到非可空属性,触发空值异常。
排查与修复步骤:
- 检查用户表数据:
直接查询数据库的AspNetUsers表,找到调用FindByNameAsync对应的用户记录,重点检查NormalizedUserName、Email、SecurityStamp、ConcurrencyStamp这些Identity框架默认必填的字段是否为NULL。 - 修正无效数据:
如果发现NULL字段,手动更新为有效值。比如NormalizedUserName设为用户名的大写形式,不需要的Email可以设为空字符串而非NULL。 - 检查实体配置(可选):
如果自定义了User实体,确认是否有属性被错误设为非可空,但数据库允许NULL。可通过Fluent API调整:
修改后需生成迁移并更新数据库。protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 示例:将Email设为可空 modelBuilder.Entity<ApplicationUser>() .Property(u => u.Email) .IsRequired(false); } - 规范用户创建逻辑:
确保通过userManager.CreateAsync创建用户时,Identity要求的必填字段都被正确赋值。避免手动插入数据时遗漏关键字段。
内容的提问来源于stack exchange,提问作者Navneet Mitawa
相关产品推荐
相关产品推荐

