我有一个自定义属性,用于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