Authorize属性让ActionResult代码执行

时间:2012-08-31 18:37:07

标签: ajax asp.net-mvc authorization actionresult

我有一个自定义属性,我用于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使用自定义authorize属性进行修饰,如下所示:

[HttpPut]
[ValidateInput(false)]
[AjaxAuthorize]
public ActionResult Comment(string id, string comment) {
    //stuff happens here.
}

我的操作结果中会抛出异常,因为我尝试访问只有在您登录时才存在的用户信息。但是,我不明白为什么这个代码甚至被执行因为我有我的授权属性保护行动。

3 个答案:

答案 0 :(得分:1)

protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
{
    // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs. 
    filterContext.Result = new HttpUnauthorizedResult();
} 

这是HandleUnauthorizedRequest的默认实现。您可能需要分配包含所需JSON的自定义ActionResult和有效状态代码。我不确定来自HTTP上下文的直接处理请求对象是否可行。

答案 1 :(得分:1)

我最终返回了一个HTTP 418(我一直希望使用它),以便Forms Authentication模块不拦截请求。然后在我的脚本中,我查找该状态代码并将其作为未经授权的请求处理,并进行正确的重定向。

答案 2 :(得分:0)

尝试在IF块中调用base.HandleUnauthorizedRequest(filterContext);。或者只是删除ELSE块并始终调用base.HandleUnauthorizedRequest(filterContext);