如何在asp.net MVC中自动检测会话超时并重定向到登录操作



如何在会话结束后自动检测会话超时并重定向到asp.net MVC中的登录操作?

我试图从Session_End((方法重定向到登录操作,但它不起作用

protected void Session_End(Object sender, EventArgs e)
{

object USerID = this.Session["sessionUserID"];
if (USerID!=null)
{
int result = BLL.Base.UserBLL.LogOut(int.Parse(USerID.ToString()),true);
Session.Clear();

}

}

您可以使用Action过滤器来完成此操作

public class SessionExpireAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check  sessions here
if( HttpContext.Current.Session["sessionUserID"] == null ) 
{
filterContext.Result = new RedirectResult("~/Home/Index");
return;
}
base.OnActionExecuting(filterContext);
}
}

现在您可以在特定操作或控制器级别使用

[SessionExpire]
public ActionResult Index()
{
return Index();
}
[SessionExpire]
public class HomeController : Controller
{
public ActionResult Authorized()
{
return Index();
}
}

最新更新