Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core ArgumentNullException:字符串引用未设置为字符串的实例。参数名称:s System.Text.Encoding.GetBytes(字符串s)_Asp.net Core - Fatal编程技术网

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

Asp.net core ArgumentNullException:字符串引用未设置为字符串的实例。参数名称:s System.Text.Encoding.GetBytes(字符串s),asp.net-core,Asp.net Core,我使用此方法生成令牌: [HttpPost("login")] public async Task<IActionResult> login(UserForLoginDto userForLoginDto) { var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

我使用此方法生成令牌:

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

        }

请帮助修复此错误。

对于此错误,似乎是
\u config.GetSection(“AppSettings:Token”)。Value
返回null

对于
\u config.GetSection(“AppSettings:Token”)
,您需要确保您的
AppSettings.json
包含以下内容:

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

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

dotnet user-secrets set "TokenKey" "super secret key" -p API/
下面是我的代码

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

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

能否显示设置文件?
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));