验证用户后,将用户重定向回上一页

时间:2014-04-21 00:22:13

标签: c# asp.net-mvc razor

在验证用户身份后,我似乎无法弄清楚如何返回上一页。我尝试返回RedirectToLocal(returnUrl)但总是将用户带回主主页索引页面。当我使用return Redirect(returnUrl)时,它会重新加载上一页。但是,上一页的ViewBag中的对象在该点处为null。我只希望用户返回上一页,保留状态,将所有输入的数据保存在购物车结帐页面上。

2 个答案:

答案 0 :(得分:0)

如何将它们重定向到“登录”页面 - 手动或使用属性?将[Authorize]添加到控制器类是最简单的方法,默认情况下按预期工作。例如

[Authorize] public class TestController : Controller

根据您的情况,您可能希望将Authorize属性放在Action而不是整个控制器上

[Authorize]
public ActionResult ConfirmShoppingCart()

这种方法的好处还在于customization

可能的最后手段是在视图上手动放置一个条件,以呈现您的"继续"按钮(或任何您想要触发身份验证的内容)。

E.g。

@if (Request.IsAuthenticated) {
//normal proceed'

} else {
     @Html.ActionLink("Proceed", "Login", "Account", new { @returnUrl = Url.Action("ViewCart", "ShoppingCart")}, new { } )
}

答案 1 :(得分:0)

使用以下::

  [HttpPost]
        public ActionResult Login(User model, string returnUrl)
        {
            // Lets first check if the Model is valid or not

            if (ModelState.IsValid)
            {
                using (DbEntities entities = new DbEntities())
                {
                    string username = model.UserID;
                    string password = model.Password;

                    var UserAuth = db.Users.Where(x => x.UserID == model.UserID && x.Password == model.Password).FirstOrDefault();

                    // Now if our password was enctypted or hashed we would have done the
                    // same operation on the user entered password here, But for now
                    // since the password is in plain text lets just authenticate directly

                    bool userValid = entities.Users.Any(user => user.UserID == username && user.Password == password);
                    var usr = entities.Users.FirstOrDefault(x => x.UserID == username && x.Password == password);
                    if (userValid)
                    {
                        //System.Web.HttpContext.Current.Session["_SessionCompany"] = usr.DefaultCompanyID;

                        FormsAuthentication.SetAuthCookie(username, false);
                        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                            && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            //return RedirectToAction("Index", "Dossier");
                            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);
        }