全局过滤器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace UpdateService.Filter
{
public class AccessControl : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool flag = false;
List<FilterAttribute> list = filterContext.ActionDescriptor.GetFilterAttributes(false).ToList();
list.AddRange(filterContext.ActionDescriptor.ControllerDescriptor.GetFilterAttributes(false).ToList());
foreach (var item in list)
{
bool b = item.Match(new AccessControlNoFilter());
if (b == true)
{
flag = true;
break;
}
}
if (flag == true)
{
base.OnActionExecuting(filterContext);
}
else
{ HttpContextBase context = filterContext.HttpContext;
HttpResponseBase response = filterContext.HttpContext.Response;
HttpRequestBase request = filterContext.HttpContext.Request;
if (context.Session["User"] == null)
{
if (request.IsAjaxRequest())
{ HttpUnauthorizedResult httpStatus = new HttpUnauthorizedResult("Session Timeout");
filterContext.Result = httpStatus;
//禁用web.config中的form认证
//<!--<authentication mode="Forms">
//<forms loginUrl="~/Account/Login" timeout="2880" />
//</authentication>-->
}
else
{
ContentResult con = new ContentResult();
con.Content = "<script>alert('当前会话已超时!');location='/Home/Login';</script>";
filterContext.Result = con;
}
}
base.OnActionExecuting(filterContext);
} }
}
}

NO全局过滤器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace UpdateService.Filter
{
public class AccessControlNoFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
}
}

FilterConfig.cs

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//全局Session检查
filters.Add(new AccessControl());
}
}

Jquery:

$(function () {
// 设置jQuery Ajax全局的参数
$.ajaxSetup({
complete: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.statusText == "Session Timeout") {
alert('当前会话已超时!');
location = "/Home/Login";
} }
});
});
05-11 14:47