如何在用户存储中实现AddToRoleAsync

时间:2019-02-14 17:33:52

标签: asp.net-core asp.net-identity

使用以下用户存储:

public class UserStore : IUserStore<AspNetUsers>, IUserPasswordStore<AspNetUsers>, IUserSecurityStampStore<AspNetUsers>, ILookupNormalizer, IUserClaimStore<AspNetUsers>, IUserRoleStore<AspNetUsers>

如何实现AddToRoleAsync的实现?

我不知道自己在做什么,这是我到目前为止的烂摊子:

public async Task AddToRoleAsync(AspNetUsers user, string roleName, CancellationToken cancellationToken)
    {
        var role = await roleStore.FindByNameAsync(Normalize(roleName), cancellationToken);
        if(role != null && !string.IsNullOrEmpty(role.Name))
        {
            user.AspNetUserRoles.Add(new AspNetUserRoles()
            {
                RoleId = role.Id,
                Role = new AspNetRoles()
                {
                    Id = Guid.NewGuid().ToString(),
                    ConcurrencyStamp = Guid.NewGuid().ToString(),
                    Name = role.Name,
                    NormalizedName = role.NormalizedName
                },
                User = user,
                UserId = user.Id
            });
        }
        else
        {
            Console.WriteLine("Role doesn't exist, please create it");
        }
        await Task.CompletedTask;
    }

更新

我认为这就是我所需要的,但是确认一下就可以了。

user.AspNetUserRoles.Add(new AspNetUserRoles()
{
    RoleId = role.Id
});

0 个答案:

没有答案