【发布时间】:2014-11-17 18:52:16
【问题描述】:
我正在使用以下方法在我的 MVC 4 应用程序中处理会话到期:
第 1 步:创建以下类:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
string actonName = filterContext.ActionDescriptor.ActionName.ToLower();
if (!(controllerName.Contains("account")||(controllerName.Contains("home") && actonName.Contains("index"))))
{
// If the browser session or authentication session has expired...
if (SessionManager.Instance["PlatformId"] == null || !filterContext.HttpContext.Request.IsAuthenticated)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult { Data = "_Logon_" };
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "Controller", "Home" },
{ "Action", "TimeoutRedirect" }
});
}
}
}
base.OnActionExecuting(filterContext);
}
}
第 2 步:将其添加到 RegisterGlobalFilters,如下所示:
filters.Add(new SessionExpireFilterAttribute());
我在会话处于活动状态并且工作正常时对此进行了测试 - 在执行每个操作时它正在检查会话是否处于活动状态。但问题是我正在使用会话值在构造函数中初始化一些对象,如下所示:
public class DashboardController : BaseController
{
private DashboardService dashboardService;
public DashboardController()
{
dashboardService = new DashboardService(this.DbContext, (int)SessionManager.Instance["PlatformId"]);
}
}
当会话超时时,显然会抛出空引用异常
dashboardService = new DashboardService(this.DbContext, (int)SessionManager.Instance["PlatformId"])
在进行会话到期检查之前。我不能将所有这些初始化移动到每个动作,因为它很忙——我已经有很多动作方法。
那么有没有办法在调用构造方法时检查会话超时?请帮忙。
【问题讨论】:
标签: c# asp.net-mvc-4 session