【问题标题】:Cannot redirect role's view无法重定向角色的视图
【发布时间】:2015-04-07 08:54:55
【问题描述】:

我这里有用于登录 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 语句如果有效则重定向您。你永远不会到达第二个if(如果用户是“所有者”,我认为这是你期望做的)

标签: c# asp.net-mvc roles


【解决方案1】:

我在同一个论坛上阅读了@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 控制器内的索引。希望这可以帮助!谢谢!

【讨论】:

  • 什么?你已经接受了我的确切答案并重复了它。祝你未来的问题好运
【解决方案2】:

如果有效,您的第一个 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);
}

【讨论】:

  • 它仍然将我重定向到 /_Layout.cshtml
  • 重定向到~/Shared/_Layout是什么意思?那是布局(母版页)而不是视图。您发帖时returnUrl 的值是多少。 AdminOnly 控制器的 Index.cshtml 视图中有什么?调试您的代码并查看您实际重定向到的位置。
  • 这是 AdminOnly 控制器的索引:[Authorize(Roles = "Owner")] [ActionName("Index")] public ActionResult Index() { return View(db.UserProfiles.ToList()); }
  • 方法签名无关。显示视图 - /Views/AdminOnly/Index.cshtml (假设您已经调试过它并且这是您的目标)。并使用新代码编辑您的问题 - 不要放入 cmets
猜你喜欢
  • 2022-06-14
  • 2018-09-01
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多