1.新建自定义属性类
public class BaseFilterAttribute : FilterAttribute, IAuthorizationFilter { /// <summary> /// 自定义扩展属性,验证用户登录 /// </summary> /// <param name="filterContext">AuthorizationContext 类将封装有关控制器、HTTP 上下文、请求上下文、路由数据、操作描述符和操作结果的信息。</param> public void OnAuthorization(AuthorizationContext filterContext) { if (filterContext.HttpContext == null) { throw new Exception("HTTP 上下文不存在!"); } if (filterContext.HttpContext.Session == null) { throw new Exception("服务器Session不可用!"); } if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) return; if (filterContext.HttpContext.Session[ConfigHelper.SessionCookieKey] != null) return; //if(filterContext.HttpContext.Request.Cookies[ConfigHelper.SessionCookieKey]==null) // filterContext.Result = new RedirectResult("~/Views/Account/Login.cshtml"); if (CookiesHelper.GetCookie(ConfigHelper.SessionCookieKey) == null) filterContext.Result = new RedirectResult(ConfigHelper.SessionCookieReturnUrl); } }
2.在相关的Controller类添加该自定义属性
[BaseFilter] public class PreListController : BaseController { }
3.设置不用验证的相关的方法允许匿名访问
[AllowAnonymous] public ActionResult Login() { return View(); }