【发布时间】:2021-08-03 14:12:25
【问题描述】:
我正在尝试使用 .Net 5 向 Web api 添加身份验证,但在创建令牌的方法中出现上述错误。
private string CreateToken(User user)
{
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username)
};
// The underlined error is on the line below on the GetSection method.
SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value));
SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
我之前在以前的项目中做过这个,效果很好。在相同版本的.Net中添加了相同的包。
不知道还有什么可能导致这种情况。
谢谢。
【问题讨论】:
-
那是来自
Microsoft.Extensions.Configuration的IConfiguration吗? -
这个小问题让我解决了问题。我没有意识到我正在使用 AutoMapper.Configuration 进行调用;而不是 Microsoft.Extensions.Configuration。不管怎样,谢谢你! :)
-
IConfiguration 来自 Microsoft.Extensions.Configuration.Abstractions 命名空间,所以安装它应该可以工作
-
只需将库从 Automapper.Configuration 更改为 Microsoft.Extensions.Configuration。不需要安装其他任何东西。