代码顺序为:OnAuthorization-->AuthorizeCore-->HandleUnauthorizedRequest
若是AuthorizeCore返回false时,才会走HandleUnauthorizedRequest 方法,而且Request.StausCode会返回401,401错误又对应了Web.config中的html
<authentication mode="Forms"> <forms loginUrl="~/" timeout="2880" /> </authentication>
全部,AuthorizeCore==false 时,会跳转到 web.config 中定义的 loginUrl="~/"web
public class CheckLoginAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { bool Pass = false; if (!CheckLogin.AdminLoginCheck()) { httpContext.Response.StatusCode = 401;//无权限状态码 Pass = false; } else { Pass = true; } return Pass; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); if (filterContext.HttpContext.Response.StatusCode == 401) { filterContext.Result = new RedirectResult("/"); } } }
AuthorizeAttribute的OnAuthorization方法内部调用了AuthorizeCore方法,这个方法是实现验证和受权逻辑的地方,若是这个方法返回true,浏览器
表示受权成功,若是返回false, 表示受权失败, 会给上下文设置一个HttpUnauthorizedResult,这个ActionResult执行的结果是向浏览器返回mvc
一个401状态码(未受权),可是返回状态码没什么意思,一般是跳转到一个登陆页面,能够重写AuthorizeAttribute的
HandleUnauthorizedRequestide
protected override void HandleUnauthorizedRequest(AuthorizationContext context) { if (context == null) { throw new ArgumentNullException("filterContext"); } else { string path = context.HttpContext.Request.Path; string strUrl = "/Account/LogOn?returnUrl={0}"; context.HttpContext.Response.Redirect(string.Format(strUrl, HttpUtility.UrlEncode(path)), true); } }
推荐一个很是好的介绍权限验证的入门的文章code