0

我使用的是具有.net成員資格的MVC3。 我想根據他們的角色將用戶重定向到不同的視圖。如何根據角色在登錄方法上重定向asp.net成員身份用戶

我嘗試了AccountControler控制器的LogOn方法來使用User.IsInRole(xxx),但它不起作用。 從我所看到的在這裏: Forms Authentication User.IsInRole() randomly not working in LogOn

成員資格用戶無法在方法調用(因爲它沒有登錄,在用戶cookie的日誌記錄還沒有尚未設置)

我不認爲它是相關的,但以防萬一,這是默認情況下在MVC3項目,我試圖修改的一個LogOn方法。

[HttpPost] 
    public ActionResult LogOn(LogOnModel model, string returnUrl) 
    { 
     if (ModelState.IsValid) 
     { 
      if (Membership.ValidateUser(model.UserName, model.Password)) 
      { 
       FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 
       if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") 
        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) 
       { 
        return Redirect(returnUrl); 
       } 
       else 
       { 
        return RedirectToAction("Index", "Home"); 
       } 
      } 
      else 
      { 
       ModelState.AddModelError("", "The user name or password provided is incorrect."); 
      } 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 
    } 

我的問題是: 什麼是根據自己的作用(我只是一對夫婦的角色)在登錄重定向用戶一種優雅的方式? 我看到一些建議,說「只是查詢會員資料庫」,但我認爲這不是一個正確的方法來做到這一點。

有什麼建議嗎?

謝謝!..

即插即用

回答

0

既然你掛我的問題,這裏是我發現了什麼。 User.IsInRole()從響應中獲取用戶名。由於log on操作中沒有用戶名(沒有用Model.UserName查找它),所以它不會在角色中找到用戶。如果您重定向它們,用戶信息將被添加到重定向中,並且可以按角色對用戶進行排序。 (至少我認爲這就是我發現的。)下面是你想做的事:

在您的帳戶控制器取代:

if (Membership.ValidateUser(model.UserName, model.Password)) 
{ 
    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 
    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") 
       && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) 
    { 
     return Redirect(returnUrl); 
    } 
    else 
    { 
     return RedirectToAction("Index", "Home"); 
    } 
} 

有了:

if (Membership.ValidateUser(model.UserName, model.Password)) 
{ 
    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 
    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") 
       && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) 
    { 
     return Redirect(returnUrl); 
    } 
    else 
    { 
     return RedirectToAction("Redirect", "Account"); 
    } 
} 

並添加:

public ActionResult Redirect() 
{ 
    if(User.IsInRole("Role1")) 
     return RedirectToAction("Index", "Home") 
    else if(User.IsInRole("Role2")) 
     return RedirectToAction("SomethingElse", "Home") 
    else 
     return RedirectToAction("AnotherThing", "Home") 
} 
+0

就像一個魅力!..謝謝!.. – PnP

相關問題