简体   繁体   中英

C# MVC4 Login Actions Based on Route Taken to Login

In my C# MVC4 application, I have two tabs at the top of every view. One labeled edit and the other labeled Admin. When either of these two tabs are clicked the user is redirected to a login page. In the Login ActionResult, after the user has been validated, I perform a check to see if the user belongs to specific AD groups that I use as roles. This all works correctly. My issue is trying to detect and perform actions based upon whether the user accessed login by clicking Edit or by clicking Admin.

How can I grab this information? Ive tried something like:

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

but the Url that contains is something like Account/Login .

My current code is:

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);
        }

The two tabs are created in my layout.cshtml like this:

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

I see you're not using the returnUrl parameter in your controller action, you can pass it like this:

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

In addition to this you could pass another parameter as the context, such as this:

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

And change the signature of your action to this:

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

Is that what you mean?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM