Arifullah Irfann

Arifullah Irfann

  • NA
  • 410
  • 27.1k

.asp.net webapi TokenService Value cannot be null

Sep 8 2022 4:02 AM

Getting Email From ClaimTypes in asp.net core 6 Give error "Value cannot be null"

When I use AddIdentityCore in the service the method 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 can't get the user from _userManager

services.AddIdentity<AppUser, IdentityRole>(opt =>
            {
                opt.Password.RequireNonAlphanumeric = false;
            })
            .AddEntityFrameworkStores<DataContext>()
            .AddSignInManager<SignInManager<AppUser>>();

And Give the Following 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 to save Asp.net User Rolls and assign them to the user
Here is my Token Service which creates 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);
        }
    }
}

 


Answers (1)