2015-02-07 45 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