gpt4 book ai didi

c# - ASP.NET Claim NameIdentifier Id 获取转换错误

转载 作者:太空狗 更新时间:2023-10-29 23:12:22 26 4
gpt4 key购买 nike

我对这段代码有疑问:

private async Task<object> GenerateJwtToken(string email, User user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id)
};

用户扩展 IdentityUser。问题是我得到:

Cannot convert from 'int' to 'System.Security.Claims.ClaimsIdentity'". Even for ClaimTypes.NameIdentifier i get error: "Cannot convert from 'string' to 'System.IO.BinaryReader'

如果我将 Id 更改为其他内容,例如电子邮件,或者 firstName 错误消失...找不到任何相关信息。

最佳答案

我在新的 Claim(ClaimTypes.Name, userFromRepo.Username) 的 Visual Code 上有这个错误,告诉 Argument 1: cannot convert from 'string' to 'System.IO.BinaryReader '。我的代码是这样的:

    public async Task<IActionResult> ReadUser([FromBody]UserDto userDto){

User userFromRepo = _authRepository.GetUserAsync();
//generate token for user
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("my secret key");
var tokenDescriptor = new SecurityTokenDescriptor{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
new Claim(ClaimTypes.Name, userFromRepo.Username) //error here in this ctor

}),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
};

在我的存储库方法之前添加缺少的 await 关键字后,顺便说一句,它是异步的,错误现在消失了。

    public async Task<IActionResult> ReadUser([FromBody]UserDto userDto){

User userFromRepo = await _authRepository.GetUserAsync(); //added await
//generate token for user
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("my secret key");
var tokenDescriptor = new SecurityTokenDescriptor{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
new Claim(ClaimTypes.Name, userFromRepo.Username) //error gets fixed

}),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
};

也许您遇到过类似的情况?

关于c# - ASP.NET Claim NameIdentifier Id 获取转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50588250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com