代碼順序爲:OnAuthorization-->AuthorizeCore-->HandleUnauthorizedRequest 若是AuthorizeCore返回false時,纔會走HandleUnauthorizedRequest 方法,而且Request.StausCode會返回401,401錯誤又對應了Web.config中 的 <authentication mode="Forms"> <forms loginUrl="~/" timeout="2880" /> </authentication> 全部,AuthorizeCore==false 時,會跳轉到 web.config 中定義的 loginUrl="~/" [csharp] view plaincopy 01.public class CheckLoginAttribute : AuthorizeAttribute 02. { 03. 04. protected override bool AuthorizeCore(HttpContextBase httpContext) 05. { 06. bool Pass = false; 07. if (!CheckLogin.AdminLoginCheck()) 08. { 09. httpContext.Response.StatusCode = 401;//無權限狀態碼 10. Pass = false; 11. } 12. else 13. { 14. Pass = true; 15. } 16. 17. return Pass; 18. } 19. 20. 21. 22. protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 23. { 24. base.HandleUnauthorizedRequest(filterContext); 25. if (filterContext.HttpContext.Response.StatusCode == 401) 26. { 27. filterContext.Result = new RedirectResult("/"); 28. } 29. } 30. 31. 32. 33. } AuthorizeAttribute的OnAuthorization方法內部調用了AuthorizeCore方法,這個方法是實現驗證和受權邏輯的地方,若是這個方法返回true, 表示受權成功,若是返回false, 表示受權失敗, 會給上下文設置一個HttpUnauthorizedResult,這個ActionResult執行的結果是向瀏覽器返回 一個401狀態碼(未受權),可是返回狀態碼沒什麼意思,一般是跳轉到一個登陸頁面,能夠重寫AuthorizeAttribute的 HandleUnauthorizedRequest [csharp] view plaincopy 01.protected override void HandleUnauthorizedRequest(AuthorizationContext context) 02. { 03. if (context == null) 04. { 05. throw new ArgumentNullException("filterContext"); 06. } 07. else 08. { 09. string path = context.HttpContext.Request.Path; 10. string strUrl = "/Account/LogOn?returnUrl={0}"; 11. 12. context.HttpContext.Response.Redirect(string.Format(strUrl, HttpUtility.UrlEncode(path)), true); 13. 14. } 15. 16. }