首页 文章

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

提问于
浏览
1

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

[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);
        }
    }

1 回答

  • 5

    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 类添加到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 Context,因此请在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;
        }
    

    完成此操作后,您可以使用var roles = RoleManager.Roles获取所有角色的列表;

    您可以根据您的要求使用它 .

相关问题