一、自定义一个Action过滤器
public class CheckSession: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
object[] attrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(NoFilter), true);
if (attrs.Length == 1){}
else {
if (filterContext.HttpContext.Session != null)
{
if (filterContext.HttpContext.Session.IsNewSession)
{
var loginUser = filterContext.HttpContext.Session["User"];
if (loginUser == null)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new RedirectResult("/GY_User/LoginIndex");
}
else
{
filterContext.Result = new JsonResult
{
Data = new
{
Success = false,
Message = string.Empty,
Redirect = "/GY_User/LoginIndex"
}
};
}
}
}
}
}
// base.OnActionExecuting(filterContext);
}
}
//不想使用全局过滤器可使用此标签
public class NoFilter:Attribute
{
public NoFilter() { }
}
二、注册全局过滤器
在FilterConfig中添加
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// filters.Add(new HandleErrorAttribute());
filters.Add(new CheckSession());
}
在Global.asax中添加
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
三、在不想使用全局过滤器的Action上添加[NoFilter]标签
四、设置Session过期时间
Session["User"] = jsonData.data;
Session.Timeout = 3;