在身份 asp mvc 中查找用户角色

find user role in identity asp mvc

我正在使用此代码登录。如何在用户登录时找到用户角色?

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {

        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var user = await UserManager.FindByNameAsync(model.Username);
        if (user != null)
        {
            if (!await UserManager.IsEmailConfirmedAsync(user.Id))
            {
                ViewBag.errorMessage = "You must have a confirmed email to log on.";
                return View("Error");
            }
        }
        var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

user.Roles 将获取用户所属的角色列表。根据您的要求,您可以执行以下操作

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{

    if (!ModelState.IsValid)
    {
        return View(model);
    }
    var user = await UserManager.FindByNameAsync(model.Username);
    if (user != null)
    {
        if (!await UserManager.IsEmailConfirmedAsync(user.Id))
        {
            ViewBag.errorMessage = "You must have a confirmed email to log on.";
            return View("Error");
        }
    }
    var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:
            if(await UserManager.IsInRoleAsync(user.Id,"Admin")) //<= Checking Role and redirecting accordingly.
                return RedirectToAction("Index", "Admin");
            else
                return RedirectToAction("Index", "User");
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}

根据我们的讨论,如果您想从数据库中获取所有角色,您需要执行以下操作

ApplicationRoleManager class 添加到您的 IdentityConfig.cs 如下

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> store)
        : base(store)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        var manager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
        return manager;
    } 
}

将 RoleManager 分配给 Owin 上下文,因此将下面添加到 starup.auth.cs

public void ConfigureAuth(IAppBuilder app)
    {
     // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
        //other code here
}

在AccountController.cs中添加一个属性

    private ApplicationRoleManager _roleManager;

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

在构造函数中传递

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager,ApplicationRoleManager roleManager )
    {
        UserManager = userManager;
        SignInManager = signInManager;
        RoleManager = roleManager;
    }

完成此操作后,您可以使用以下方法获取所有角色的列表 变量角色 = RoleManager.Roles;

您可以根据需要使用它。