Getting Email From ClaimTypes in asp.net core 6 Give error "Value cannot be null"
When i use AddIdentityCore in the service the methode for geting the current login user from _userManager
Working Fine
var user = await _userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email));
services.AddIdentityCore<AppUser>(opt =>
{
opt.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<DataContext>()
.AddSignInManager<SignInManager<AppUser>>();
But if i change the AddIdentityCore to AddIdentity as below then cant get the user from _userManager
services.AddIdentity<AppUser, IdentityRole>(opt =>
{
opt.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<DataContext>()
.AddSignInManager<SignInManager<AppUser>>();
And Give the Follwoing Error
"statusCode": 500,
"message": "Value cannot be null. (Parameter \u0027email\u0027)",
"details": " at Microsoft.AspNetCore.Identity.UserManager\u00601.FindByEmailAsync(String email)
I want to use IdentityRole in service to allow me save Asp.net User Rolls and assign them to user
Here is my Token Service which create JWT Token
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
namespace API.Services
{
public class TokenService
{
private readonly IConfiguration _config;
public TokenService(IConfiguration config)
{
_config = config;
}
public string CreateToken(AppUser user)
{
var claim = new List<Claim>
{
new Claim(ClaimTypes.Name,user.UserName),
new Claim(ClaimTypes.NameIdentifier,user.Id),
new Claim(ClaimTypes.Email,user.Email),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["MyTokenKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claim),
Expires = DateTime.Now.AddDays(7),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}