【发布时间】:2012-08-31 18:37:07
【问题描述】:
我有一个用于 Ajax 请求的自定义属性,以防止发生默认的 FormsAuthentication 工作流(因为它对 Ajax 请求没有意义)。
这是自定义的授权属性:
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.
}
在我的操作结果中引发了异常,因为我尝试访问有关用户的信息,该信息仅在您登录时才存在。但是,我不明白为什么要执行此代码,因为我有我的授权保护动作的属性。
【问题讨论】:
-
我知道这是一个非常古老的线程,但你找到答案了吗。
-
@BhargavKonda 是的,请查看我发布的问题的答案。
标签: ajax asp.net-mvc authorization actionresult