代碼順序爲: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