我有一個自定義屬性,用於Ajax請求以防止默認的FormsAuthentication工作流發生(因爲它對Ajax請求沒有意義)。授權屬性讓ActionResult代碼執行
這是自定義授權屬性:
public class AjaxAuthorize : AuthorizeAttribute {
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
UrlHelper urlHelper;
if (filterContext.HttpContext.Request.IsAjaxRequest()) {
urlHelper = new UrlHelper(filterContext.RequestContext);
filterContext.HttpContext.Response.StatusCode = 401;
//Don't let IIS7 be mean.
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
//Return JSON which tells the client where the login page exists if the user wants to authenticate.
filterContext.HttpContext.Response.Write(new JavaScriptSerializer().Serialize(
new {
LoginUrl = string.Format("{0}?ReturnURL={1}", FormsAuthentication.LoginUrl, urlHelper.Encode(filterContext.HttpContext.Request.Url.PathAndQuery))
}
));
filterContext.HttpContext.Response.End();
} else {
base.HandleUnauthorizedRequest(filterContext);
}
}
}
我有我的ActionResult飾以自定義授權屬性,像這樣:
[HttpPut]
[ValidateInput(false)]
[AjaxAuthorize]
public ActionResult Comment(string id, string comment) {
//stuff happens here.
}
一個例外是我行動的結果裏面扔,因爲我嘗試訪問有關用戶的信息,只有當您登錄時纔會存在。但是,我不明白爲什麼此代碼甚至被執行,因爲我的授權屬性保護了該操作。
我使用了419身份驗證超時(不在RFC 2616中)。這有助於我走上正軌。 – GameSalutes