无法重定向角色的视图

Cannot redirect role's view

我这里有这些代码用于登录 POST 和 GET

[Authorize]
public class AccountController : Controller
{
    //
    // GET: /Account/Login

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            return RedirectToLocal(returnUrl);
        }


        if (User.IsInRole("Owner"))
        {
            return RedirectToAction("Index", "AdminOnly");
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

但是,我的问题是,当我尝试登录管理员帐户时,我被重定向到 ~/Shared/Layout。我应该怎么办?提前致谢!

您的第一个 if 语句如果有效则立即重定向用户。由于您已经退出该方法,因此您永远无法检查他们的角色。在重定向之前更改您的方法以测试用户角色

public ActionResult Login(LoginModel model, string returnUrl)
{
  if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
  {
    if (User.IsInRole("Owner"))
    {
      return RedirectToAction("Index", "AdminOnly");
    }
    else
    {
      return RedirectToLocal(returnUrl);
    }
  }
  ModelState.AddModelError("", "The user name or password provided is incorrect.");
  return View(model);
}

我在同一论坛上阅读了@KurtSchindler 的回答。这个代码块很有魅力

  if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            string[] roles = Roles.GetRolesForUser(model.UserName);
            if (roles.Contains("Owner") || roles.Contains("Superuser"))
            {
                return RedirectToAction("Index", "AdminOnly");
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

它现在将我重定向到 AdminOnly 控制器内的索引。希望这可以帮助!谢谢!