自定义授权属性仅适用于localhost

时间:2012-08-31 16:50:58

标签: c# ajax asp.net-mvc json authentication

我有一个用于Ajax请求的自定义authorize属性:

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;
            //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);
        }
    }
}

当我在本地运行应用程序时,我从Ajax请求中获取JSON结果。但是,当我将代码放在我的beta服务器上时,我最终获得了IIS 401 HTML响应。

有没有人发现我的代码有问题会使这个只能在localhost上运行?另外,如果有人有更好的想法返回JSON结果,我也会对此持开放态度。

1 个答案:

答案 0 :(得分:4)

StackOverflow有一些奇怪的力量导致OP在发布后以不同的方式思考问题。我会在这里留下我的答案,希望它可能使其他人受益。

我刚刚想到IIS7正在阻碍它。我通过添加一行代码来修复此问题:

filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;