1

我正在使用 asp.net core 1.1 和 identity 1.1。我的应用程序中有 2 个角色包含“管理员”和“用户”。我希望“管理员”用户在登录后导航到“/AdminProfile/Index”,“用户”用户在登录后导航到“/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 操作中:

    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 中的用户角色?

4

1 回答 1

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

        }
    }
于 2018-01-17T00:24:02.070 回答