2015-02-07 44 views
-1

我在这里有这些代码的登录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); 
    } 

我的问题,但是,当我尝试登录管理员帐户,我得到重定向到〜/共享/布局。我该怎么办?提前致谢!

+0

如果你的第一个'if'语句有效,你会重定向你。你永远不会到达第二个“if”(假设用户是“所有者”,你的期望是如何) – 2015-02-07 05:40:31

回答

-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控制器内的索引。希望这可以帮助!谢谢!

+0

什么?你已经采取了我确切的答案,并重复它。祝你今后的问题好运 – 2015-02-09 05:17:44

0

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

它仍然将我重定向到/_Layout.cshtml – bampie 2015-02-07 06:13:06

+0

你是什么意思它重定向到“〜/ Shared/_Layout'?这是一个布局(母版页)而不是视图。发布时'returnUrl'的价值是多少? AdminOnly控制器的'Index.cshtml'视图中有什么?调试您的代码并查看您实际重定向到的位置。 – 2015-02-07 06:17:25

+0

这是AdminOnly控制器的索引:[[Authorize(Roles =“Owner”)] [ActionName(“Index”)] public ActionResult Index() { return View(db.UserProfiles.ToList()) ; }' – bampie 2015-02-07 06:26:22