注销后,我的应用程序允许我创建,编辑和删除用户。尽管我在用户身份验证后不久就创建了会话变量,并且在注销时也将其删除。但是在mvc4中,我无法弄清楚在何处检查这些会话变量条件(是否为null)。就像在asp.net(c#)page_load中一样,我们可以在其中执行if条件的页面。
整个互联网上,人们在讨论有关使用Java脚本禁用浏览器后退按钮以及删除cookie的问题,但在我的情况下,一旦用户注销,是否使用浏览器后退按钮查看内容,如果单击该按钮,则应重定向到登录页面。
有人可以协助我找到正确的位置来检查会话变量为空的条件。是风景吗?它是share_layout视图吗?还是控制器?还是我没有其他提示,请帮忙。
这是我的会话控制器代码
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult LogIn(User user)
{
try
{
if (ModelState.IsValid)
{
var userdb = db.User.Include("Role").Single(c => c.userName == user.userName);
if (userdb.passWord == user.passWord)
{
Session["UserId"] = userdb.userId;
Session["UserName"] = userdb.userName;
Session["RoleName"] = userdb.Role.roleName;
if (userdb.Role.roleName == "Employee")
{
return RedirectToAction("Index", "Employee");
}
else if (userdb.Role.roleName == "Customer")
{
return RedirectToAction("Index", "CustomerSite");
}
else if (userdb.Role.roleName == "Admin")
{
return RedirectToAction("Index", "Admin");
}
}
else
{
ViewBag.errorMsg = "We cannot authenticate you please use the right username or password";
return View();
}
}
return View();
}
并注销
public ActionResult Logout()
{
Session.Remove("UserId");
Session.Remove("UserName");
Session.Remove("RoleName");
return RedirectToAction("LogIn", "Session");
}
从理论上讲,您想使用FormAuthentication。它与默认的AuthorizeAttribute开箱即用。
如果要实现自己的逻辑,则可以覆盖AuthorizeAttribute。
这里的例子-
public class MyAuthorizeAttribute : AuthorizeAttribute
{
private bool AuthorizeUser(AuthorizationContext filterContext)
{
bool isAuthorized = false;
if (filterContext.RequestContext.HttpContext != null)
{
var context = filterContext.RequestContext.HttpContext;
if(context.Session["UserId"] != null)
isAuthorized = true;
}
return isAuthorized;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
throw new ArgumentNullException("filterContext");
if (AuthorizeUser(filterContext))
return;
base.OnAuthorization(filterContext);
}
}
[MyAuthorizeAttribute]
public class MyController : Controller
{
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句