Identity Db Context Get Null In Web API
I have created API in .net 7.0, I have EF core with IdentityDbContext
. Problem is when I am going to find user by user manager as below get null exception.
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)
I have tried to get user in login action.
[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();
}
Comments
Post a Comment