ArgumentNullException:未将字符串引用设置为字符串的实例。参数名称:s System.Text.Encoding.GetBytes(string s)

Jsp*_*o30 3 asp.net-core

我有这个方法来生成令牌:

[HttpPost("login")]
        public async Task<IActionResult> login(UserForLoginDto userForLoginDto)
        {
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

            if(userFromRepo == null)
               return Unauthorized();

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };   

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return Ok(new{
                token = tokenHandler.WriteToken(token)
            });

        }
Run Code Online (Sandbox Code Playgroud)

当我通过邮递员调用此 API 时:

本地主机:5000/api/auth/登录

在正文中用户名:“john”,密码:“password”

我收到这个错误:

处理请求时发生未处理的异常。ArgumentNullException:未将字符串引用设置为字符串的实例。参数名称:s System.Text.Encoding.GetBytes(string s)

因为这一行:

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));
Run Code Online (Sandbox Code Playgroud)

请帮助修复此错误。

Tao*_*hou 9

对于这个错误,似乎_config.GetSection("AppSettings:Token").Value返回null。

对于_config.GetSection("AppSettings:Token"),您需要确保您appsettings.json包含以下内容:

{
"AppSettings": {
    "Token": "This is Token"
},   
}
Run Code Online (Sandbox Code Playgroud)