【问题标题】:ArgumentNullException: String reference not set to an instance of a String. Parameter name: s System.Text.Encoding.GetBytes(string s)ArgumentNullException:字符串引用未设置为字符串的实例。参数名称:s System.Text.Encoding.GetBytes(string s)
【发布时间】:2019-12-07 18:35:59
【问题描述】:

我有这个生成token的方法:

[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)
            });

        }

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

localhost:5000/api/auth/login

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

我收到了这个错误:

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

因为这条线:

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

请帮助解决此错误。

【问题讨论】:

  • 你能显示你的设置文件吗?

标签: asp.net-core


【解决方案1】:

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

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

{
"AppSettings": {
    "Token": "This is Token"
},   
}

【讨论】:

    【解决方案2】:

    我得到了这个确切的错误,我正在使用 VS Code。我通过设置一个名为“tokenkey”的环境变量解决了这个问题,这可以使用以下方法在终端中设置:

    dotnet user-secrets set "TokenKey" "super secret key" -p API/
    

    下面是我的代码

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));
    

    如果您在生产模式下遇到此错误,则必须在服务器上设置环境变量。

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 2020-06-14
      • 1970-01-01
      • 2011-08-19
      • 2010-09-24
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多