public class CustomAuthorzieAttribute : AuthorizeAttribute
{ private string _controllerName = string.Empty;/// <summary>
/// base.OnAuthorization(filterContext)中会调用AuthorizeCore函数 /// 当AuthorizeCore返回false,则会继续调用HandleUnauthorizedRequest进行处理 /// 所以OnAuthorization是该类的总入口 /// </summary> /// <param name="filterContext"></param> public override void OnAuthorization(AuthorizationContext filterContext) { //程序过滤器入口处//获取当前访问页面所属控制器名称
_controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;base.OnAuthorization(filterContext);
} /// <summary> /// base.OnAuthorization来调用 /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { //登陆界面,允许匿名访问,不用身份认证,直接返回true if (_controllerName.ToLower() == "login") { return true; } //获取当前登陆主体标识信息 var dien = httpContext.User.Identity;//判断,如果验证登陆通过,直接返回true
if (dien.IsAuthenticated) { return true; } else //否则拒绝访问 false { return false; } } // <summary> /// 当AuthorizeCore返回false时候调用 /// </summary> /// <param name="filterContext"></param> protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); }