对用户进行身份验证后,将用户重定向回上一页
本文关键字:用户 重定向 一页 身份验证 | 更新日期: 2023-09-27 17:59:12
我似乎不知道如何在对用户进行身份验证后返回到上一页。我尝试返回RedirectToLocal(returnUrl),但这总是将用户带回主索引页。当我使用return Redirect(returnUrl)时,它会重新加载上一页。但是,上一页的ViewBag中的对象在该点为null。我只想让用户返回到上一个页面,保留State,将所有输入的数据保留在购物车结账页面上。
如何将它们重定向到登录页面-手动或使用属性?将[Authorize]
添加到控制器类是最简单的方法,默认情况下可以按预期工作。例如
[Authorize]
public class TestController : Controller
对于您的情况,您可能希望将Authorize属性放在Action上,而不是放在整个控制器上
[Authorize]
public ActionResult ConfirmShoppingCart()
这种方法的好处是进一步定制
最后一种可能的方法是在呈现"继续"按钮的视图上手动设置条件(或任何您想要触发身份验证的条件)。
例如
@if (Request.IsAuthenticated) {
//normal proceed'
} else {
@Html.ActionLink("Proceed", "Login", "Account", new { @returnUrl = Url.Action("ViewCart", "ShoppingCart")}, new { } )
}
使用以下内容::
[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);
}