我有一个用于 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.
}
我的操作结果中引发了异常,因为我尝试访问有关用户的信息,该信息仅在您登录时才存在。但是,我不明白为什么甚至要执行此代码,因为我有我的授权属性来保护行动。