Asp Core,检查用户是否在Identity 1.1中的角色?

时间:2018-01-16 16:34:29

标签: asp.net-mvc asp.net-core asp.net-identity role-base-authorization

我使用的是asp.net核心1.1和身份1.1。我的应用程序中有2个角色包含“Admin”和“User”。我希望登录后“Admin”用户导航到“/ AdminProfile / Index”,登录后“User”用户导航到“/ UserProfile / Index”。

我的登录代码:

    [HttpGet]
    public IActionResult Login(string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        return View();
    }


    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;

        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Error");
                return View(model);
            }
        }
        return View(model);
    }

在RedirectToLocal Action中:

    private IActionResult RedirectToLocal(string returnUrl)
    {
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        else
        {

            if (User.IsInRole("Admin"))
            {
                return Redirect("/AdminProfile/Index");
            }
            else
            {
                return Redirect("/UserProfile/Index");
            }

        }
    }

我使用User.IsInRole("Admin")来验证用户角色,但它总是返回false。如何检查身份1.1中的用户角色?

1 个答案:

答案 0 :(得分:1)

经过多次研究,我可以解决它。试试吧:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                var user = await _userManager.FindByNameAsync(model.UserName);
                string existingRole = _userManager.GetRolesAsync(user).Result.Single();

                return RedirectToLocal(returnUrl,existingRole);
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Error");
                return View(model);
            }
        }
        return View(model);
    }





    private IActionResult RedirectToLocal(string returnUrl,string roleName)
    {
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        else
        {
            if (roleName == "Admin")
            {
                return Redirect("/Admin/User");
            }
            else
            {
                return Redirect("/User/UserProfile");
            }

        }
    }