加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – CreateUserIdenityAsync返回自定义IdentityUser的“UserId

发布时间:2020-12-15 08:27:41 所属栏目:百科 来源:网络整理
导读:我正在跟随 bitoftech tutorial关于使用JWT创建基于身份和角色的声明.我的应用程序用户是一个带有int PK的自定义User表. 目前,GenerateUserIdentityAsync方法只返回一个奇怪的UserId not found错误.这是我的代码: ClaimsIdentity oAuthIdentity = await use
我正在跟随 bitoftech tutorial关于使用JWT创建基于身份和角色的声明.我的应用程序用户是一个带有int PK的自定义User表.

目前,GenerateUserIdentityAsync方法只返回一个奇怪的UserId not found错误.这是我的代码:

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,"JWT");

和用户实体中的实现:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User,int> manager,string authenticationType)
{
    //error on this line: CreateIdentityAsync throws error
    var userIdentity = await manager.CreateIdentityAsync(this,authenticationType);
    return userIdentity;
}

我的UserManager类定义如下:

public class AppUserManager : UserManager<User,int>

奇怪的是,当我调试时,GenerateIdentityAsync中的实例确实有一个UserId属性,但是只有一个id,我想知道这是不是错误的地方? (听起来不对)

我正在查看source code(第80行),但我无法弄清楚抛出异常的位置.

抛出的确切异常是:

UserId not found. 
 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: 
    System.InvalidOperationException: 
    UserId not found.

stack trace并不是那么有用(对我而言)

如何找出UserId不可用的原因/位置?

模式细节:

我的GrantResourceOwnerCredentials():

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",new[] {"*"});

    var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
    User user = await userManager.FindAsync(context.UserName,context.Password);

    if (user == null) // this is NOT null
    {
        context.SetError("invalid_grant","The username or password is incorrect");
        return;
    }

    // this line fails
    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,"JWT"); 
    var ticket = new AuthenticationTicket(oAuthIdentity,null);
    context.Validated(ticket);
}

和ApplicationUser(在我的例子中,只是用户)

public partial class User : IdentityUser<int,CustomUserLogin,CustomUserRole,CustomUserClaim>
{  
    public int UserId { get; set; }
    public string Fullname { get; set; }
    public string Address { get; set; }
    public string ContactNumber { get; set; }
}

解决方法

正如您在调试时发现的那样,IdentityUser有一个Id,在您的情况下,它代表用户的ID.

您需要从User类中删除UserId,使用IdentityUser中的基本ID并将自定义User表中的UserId列重命名为Id.

您的User类中的任何属性都需要在数据库的用户表中具有匹配的列.如果没有,那么对于不匹配的属性,您将得到相同的错误.

这意味着Fullname,Address和ContactNumber必须在AspNetUsers表中具有匹配的列名,否则您也将获得这些属性的相同错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读