我遇到频繁的会话超时问题。
我想编写一个可以在每个控制器上使用的公共过滤器,过滤器应该将用户重定向到登录,并在登录后返回用户发送最后一个请求的位置。
答案 0 :(得分:5)
您可以尝试这样的事情:
public class SessionExpireAttribute : ActionFilterAttribute {
public override void OnActionExecuted(ActionExecutedContext filterContext) {
base.OnActionExecuted(filterContext);
}
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if (filterContext.HttpContext.Session != null) {
if (filterContext.HttpContext.Session.IsNewSession) {
var sessionCookie = filterContext.HttpContext.Request.Headers["Cookie"];
if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) {
// redirect to login
}
}
}
}
}
答案 1 :(得分:1)
在这里,不仅仅是满足于眼睛。这是一个更完整的OnActionExecuting,它使用了上面已经讨论过的相同概念,但增加了一些。有关详细信息,请参阅内联注释。 " InitializeSession"被调用是一个自定义函数,它创建会话状态中运行站点所需的基本属性。 " AlertWarning"是帮助显示警报的例程。其他一切都是样板代码。
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var bRequiresAuthorization =
(filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), false).Length > 0) ||
(filterContext.Controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), false).Length > 0);
if (filterContext.HttpContext.Session != null)
{
if (filterContext.HttpContext.Session.IsNewSession)
{
//New session. Initialize Session State
bool b = InitializeSession(null);
if (bRequiresAuthorization )
{
//Action requested requires authorized access. User needs to authenticate this
//new session first, so redirect to login
string cookie = filterContext.HttpContext.Request.Headers["Cookie"];
if ( (cookie != null) && (cookie.IndexOf("_SessionId=") >= 0) )
{
//An expired session cookie still resides on this PC, so first alert user that session is expired
AlertWarning("Session timed out due to inactivity. Please log in again.");
}
filterContext.Result = RedirectToAction("LogOut", "Authentication");
}
}
}
base.OnActionExecuting(filterContext);
}
答案 2 :(得分:0)
您是否尝试过现有的授权过滤器?
答案 3 :(得分:0)
如上所述..试试这个
public class SessionExpireAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if (filterContext.HttpContext.Session != null) {
if (filterContext.HttpContext.Session.IsNewSession) {
filterContext.Result = new RedirectResult("/");//redirect to home page
}
}
}
}
然后将此过滤器应用于操作或控制器[SessionExpire]