添加前检查用户是否存在角色 [英] Checking role exists for user before add

查看:68
本文介绍了添加前检查用户是否存在角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为用户添加角色,但是在此之前我想检查它是否存在.我怎样才能做到这一点? 这是我的代码

I am trying to add roles for user but before that i want to check it is exists or not. How Can i do that? Here is my code

  public void AddRoleForUser(ApplicationUser obj, IdentityRole role)
    {
        _userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(_context));

        var currentUser = _userManager.FindById(obj.Id);
        // before this i have to check 
        var roleresult = _userManager.AddToRole(currentUser.Id, role.Name);
    }

例如,我有一个用户,其ID = 1.当我为此用户添加角色时,我想先检查该用户是否有角色,然后再向该用户添加新角色

for example i have a user and its id =1. When i add role for this user i want to check there is a role for this user before add new role to this user

推荐答案

您只需要检查User.IsInRole("YourRoleName");

如果要通过 User Id 进行检查,请使用下面的代码.

If you want to check by User Id, use the code below.

if (!userManager.IsInRole(user.Id, "Admin"))
{
    userManager.AddToRole(user.Id, "Admin");
}

这篇关于添加前检查用户是否存在角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆