自定义Authorize

来源:互联网 发布:网络巡检报告 编辑:程序博客网 时间:2024/05/16 11:36

自定义Authorize:

用于判断网站的权限,查看当前用户有无权限访问。

创建一个类继承于AuthorizeAttribute

public class ZDYAuthorizeAttribute : AuthorizeAttribute

想要实现自定义Authorize,得重写一下虚方法:

public virtual void OnAuthorization(AuthorizationContext filterContext);//在过程请求授权时调用。protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);//<span style="font-family: Arial, Helvetica, sans-serif;">处理未能授权的 HTTP 请求。</span>protected virtual bool AuthorizeCore(HttpContextBase httpContext);//<span style="font-family: Arial, Helvetica, sans-serif;">重写时,提供一个入口点用于进行自定义授权检查。</span>
重写方法OnAuthorization

 public override void OnAuthorization(AuthorizationContext filterContext)        {            if(filterContext == null)            {                throw new ArgumentNullException("filterContext");//处理filterContext出错            }            if(!AuthorizeCore(filterContext.HttpContext))//处理是否已经验证了,返回false:未验证  true:已验证            {                HandleUnauthorizedRequest(filterContext);//处理未授权的的Http对象,重写使它转向另外一个页面(比如登录界面)            }            else            {                filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);//清除缓存            }        }
重写方法HandleUnauthorizedRequest
 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)        {            if(filterContext == null)//处理错误            {                throw new ArgumentNullException("filterContext");            }            else            {                string path = filterContext.HttpContext.Request.Path;                string strUrl = "/Account/Login?returnUrl={0}";//利用链接进入未授权的页面,使其跳转到登录页面                filterContext.HttpContext.Response.Redirect(string.Format(strUrl,HttpUtility.UrlEncode(path)),true);            }        }
处理未能授权的http请求,在这里只是将其页面跳转到登录页面,还有其他的处理方法,视情况而定
重写方法AuthorizeCore

protected override bool AuthorizeCore(HttpContextBase httpContext)        {            if (httpContext == null)                throw new ArgumentNullException("httpContext");//错误处理            else                return CLogin.isAuthenticated();//根据登录页面传回来的bool来确定是否授权        }
该方法决定当前用户是否有权限



0 0