C# 在生成访问令牌时,如何将userid参数添加到jwt的负载中?

C# 在生成访问令牌时,如何将userid参数添加到jwt的负载中?,c#,asp.net-mvc,asp.net-core,jwt,C#,Asp.net Mvc,Asp.net Core,Jwt,生成访问令牌时,如何将userId参数添加到jwt的有效负载中 我使用的是asp.net core 2.2,我需要将userId参数添加到生成访问令牌的有效负载中,然后将结果生成为JSON public string GenerateTokens(string userId) { var Claims = new Claim[] { new Cla

生成访问令牌时,如何将
userId
参数添加到
jwt
的有效负载中

我使用的是
asp.net core 2.2
,我需要将
userId
参数添加到生成访问令牌的有效负载中,然后将结果生成为JSON

  public string GenerateTokens(string userId)
            {    
                var Claims = new Claim[]
                         {
                new Claim(JwtRegisteredClaimNames.Sub,userId)
                         };
                var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is secret phrase"));
                var SigningCredntials = new SigningCredentials(signingkey, SecurityAlgorithms.HmacSha256);
                var Jwt = new JwtSecurityToken();

                return new JwtSecurityTokenHandler().WriteToken(Jwt);
            }

您应该在初始化
JwtSecurityToken
实例时设置声明:

var Claims = new Claim[]
{
    new Claim(JwtRegisteredClaimNames.Sub,"userid")
     //your other claims
};
var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is secret phrase"));
var SigningCredntials = new SigningCredentials(signingkey, SecurityAlgorithms.HmacSha256);
var Jwt = new JwtSecurityToken(claims:Claims,signingCredentials:SigningCredntials);

return new JwtSecurityTokenHandler().WriteToken(Jwt);
JwtSecurityToken
的构造函数,它还可以设置
问题
受众
过期

public JwtSecurityToken(string issuer = null, string audience = null, IEnumerable<Claim> claims = null, DateTime? notBefore = null, DateTime? expires = null, SigningCredentials signingCredentials = null);
public JwtSecurityToken(字符串颁发者=null,字符串受众=null,IEnumerable声明=null,DateTime?notBefore=null,DateTime?expires=null,签名凭证签名凭证=null);

是否有什么不清楚的地方?添加用户id如何?我发现用户id不存在于用户id参数上方的函数中,因此我需要添加用户id。请如何操作?这是一件好事,但这意味着什么JwtRegisteredClaimNames.SubAny错误问题?如果回答帮助,请考虑标记作为答案。