2013-04-21 54 views
3

在我的C#MVC4應用程序中,每個視圖頂部都有兩個選項卡。一個標記爲編輯,另一個標記爲管理員。當點擊這兩個標籤中的任何一個時,用戶將被重定向到登錄頁面。在Login ActionResult中,驗證用戶後,我執行檢查以查看用戶是否屬於我用作角色的特定AD組。這一切正常工作。我的問題是嘗試根據用戶是通過單擊「編輯」還是單擊「管理員」訪問登錄來檢測和執行操作。C#MVC4基於採取的路由登錄操作

我該如何獲取這些信息?我試過類似的東西:

if(HttpContext.Request.UrlReferrer.OriginalString.Contains("Edit")) 

但包含的網址是類似於Account/Login

我當前的代碼是:

public ActionResult Login(LoginModel model, string returnUrl) 
     { 
      //Checks if user exists in Active Directory 
      if (ModelState.IsValid && Membership.ValidateUser(model.UserName, model.Password)) 
      { 
        //Logs user in by creating a cookie 
        FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 

        //Checks to see if user belongs to a group with Edit or Admin Priviledges 
        if ((Roles.IsUserInRole(model.UserName,"TCL-CAdmin")) || (Roles.IsUserInRole(model.UserName, "TCL-CGroup"))) 
        { 
         return RedirectToAction("Index", "Home"); 
        } 
        else 
        { 
         return RedirectToAction("Index_Perm", "Home"); 
        } 
       } 
      ModelState.AddModelError("", "The user name or password provided is incorrect."); 
      return View(model); 
     } 

的兩個選項卡在我layout.cshtml創建這樣的:

<ul id="menu"> 
         <li>@Html.ActionLink("Edit", "Login", "Account")</li> 
         <li>@Html.ActionLink("Admin", "Admin", "Home")</li> 
        </ul> 

回答

1

我看到你沒有使用returnUrl參數在你的控制器動作,你可以這樣傳遞:

@Url.Action("Login", "Account", new { returnUrl = Request.RawUrl })

除了這個,你可以通過其他參數作爲背景下,像這樣的:

@Url.Action("Login", "Account", new { returnUrl = Request.RawUrl, context = "Edit" })

,改變你的行動來此簽名:

public ActionResult Login(LoginModel model, string returnUrl, string context)

這就是你意思?

+0

我認爲你的回答是正確的,我不知道如何使用returnUrl參數,因爲我相當新的這個。如果我理解你的建議,我應該嘗試這樣:[

  • @ Html.ActionLink(「編輯」,「登錄」,「帳戶」,新{returnUrl = Request.RawUrl})
  • ]代替顯示的新代碼Ive以上。 – HendPro12 2013-04-21 22:37:25

    +0

    是的,應該工作,'Url.Action'方法只返回URL,而不是'a'標籤。所以你需要使用'@ Url.Action(「Login」,「Account」,new {returnUrl = Request.RawUrl})'Edit'等 – greg84 2013-04-21 22:38:49

    +0

    '我在returnUrl中得到一個值/ – HendPro12 2013-04-21 23:36:10