1.0 創建Attribute using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LSUnion.Site.WebHelper { [AttributeUsag
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());//增加自己定義的過濾器 } } }