標籤:http io ar 使用 for sp div on art
代碼順序為: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="~/"
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)
{
if(filterContext.HttpContext.Request.IsAjaxRequest())
{
if (!App.AppService.IsLogon)
{
filterContext.Result = new JsonResult
{
Data = new {IsSuccess = false, Message = "不好意思,登入逾時,請又一次登入再操作!"},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
return;
}
}
if (App.AppService.IsLogon)
{
return;
}
base.HandleUnauthorizedRequest(filterContext);
if (filterContext.HttpContext.Response.StatusCode == 401)
{
filterContext.Result = new RedirectResult("/");
}
}
}
AuthorizeAttribute的OnAuthorization方法內部調用了AuthorizeCore方法,這種方法是實現驗證和授權邏輯的地方,假設這種方法返回true,
表示授權成功,假設返回false, 表示授權失敗, 會給上下文設定一個HttpUnauthorizedResult,這個ActionResult啟動並執行結果是向瀏覽器返回
一個401狀態代碼(未授權),可是返回狀態代碼沒什麼意思,一般是跳轉到一個登入頁面,能夠重寫AuthorizeAttribute的
HandleUnauthorizedRequest
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);
}
}
MVC中使用AuthorizeAttribute做身分識別驗證操作