1.0 创建Attribute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LSUnion.Site.WebHelper
{
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,AllowMultiple=false)]
public class CheckAdminLoginAttribute:Attribute
{
}
}
2.0 创建 CheckAdminLoginActionFilterAttribute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LSUnion.Site.Common;
namespace LSUnion.Site.WebHelper
{
public class CheckAdminLoginActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
Type checkAdminAtt = typeof(CheckAdminLoginAttribute);
//判断action或者action所在的controller是否贴有此标签
var isCheckAdminLogin = filterContext.ActionDescriptor.IsDefined(checkAdminAtt, false) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(checkAdminAtt, false);
if (isCheckAdminLogin)//如果贴有标签,检查登录
{
//先判断session
if (HttpContext.Current.Session[Keys.adminUserInfo] == null)
{
//session为空,再判断cookie是否做了免登陆
var ck = filterContext.HttpContext.Request.Cookies[Keys.isRememberAdmin];//里面可以存加密的用户Id
if (ck!=null)
{
HttpContext.Current.Session[Keys.adminUserInfo] = ck.Value;
}
else
{
ToLogin(filterContext);
}
}
}
}
private void ToLogin(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var jsonRes = new JsonResult();
jsonRes.Data = new {status = (int) Enums.EAjaxStatus.nologin, msg = "您未登录或者登录已失效!"};
filterContext.Result = jsonRes;
}
else
{
ActionResult res = new RedirectResult("/Admin/Login/index");
filterContext.Result = res;
}
}
}
}
3.0 在 App_Start里面的FilterConfig.cs中配置
using System.Web;
using System.Web.Mvc;
using LSUnion.Site.WebHelper;
namespace LSUnion.Site
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new CheckAdminLoginActionFilterAttribute());//增加自己定义的过滤器
}
}
}
4.0 给需要做登录检查的方法或者控制器加上 [CheckAdminLogin]