【问题标题】:Authorize with JsonReult action jQuery ajax returned status code 200 when not authorized使用 JsonReult 操作授权 jQuery ajax 在未授权时返回状态码 200
【发布时间】:2011-08-11 16:35:23
【问题描述】:

我有需要身份验证和特殊角色的 JsonResult 操作

[Authorize(Roles = "User")]
public virtual JsonResult Cancel()
{
 //...
}

但是,例如,当我注销并使用 jQuery ajax 执行此操作时,我可以看到状态码是 200,但它应该是 401。

$.ajax({
                url: "/Cancel/",
                type:   "POST",
                dataType: "text",
                cache: false,
                success: function (data, textStatus, xhr) {
                    alert(xhr.status); //200 here when unauthorized
                }

});

所以我真的无法执行控制器逻辑,因为它未经授权,我在调试时检查过,但为什么我在 jquery ajax 中得到状态代码 200?

更新:

在 Fiddler 中显示状态代码 302,我可以看到对 /Acount/Login 的请求是在 /Cancel 请求之后发出的。

/Cancel - 302
/Acount/Login - 200

在 Chrome 网络中找到状态码:302,我还可以看到登录控制器(/Acount/Login)在调用/Cancel 之后被调用。

/Cancel - 302
/Acount/Login - 200

Opera 网络中的完整请求详细信息

有人能解释一下发生了什么吗,为什么 jquery 没有得到正确的状态码?

我真正想要做的 - 想要获得正确的状态码,如果是 401,我想将用户重定向到登录页面 (window.location.href = " /Acount/Login")

请求详情

POST /Cancel/ HTTP/1.1 
User-Agent: Opera/9.80 (Windows NT 6.1; U; en) Presto/2.9.168 Version/11.50
Host: localhost:999
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate
Referer: http://localhost:999/Action
Cookie: style=normalText; ASP.NET_SessionId=latzewpi3kqmkq4meljv0ln5
Connection: Keep-Alive
Content-Length: 0
Accept: text/plain, */*; q=0.01
X-Requested-With: XMLHttpRequest
Content-Type: text/xml; charset=utf-8
Content-Transfer-Encoding: binary

回复详情

HTTP/1.1 302 Found 
Cache-Control: private
Content-Type: text/html; charset=utf-8
Location: /Account/LogOn?ReturnUrl=%2fCancel%2f
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 11 Aug 2011 03:04:53 GMT
Content-Length: 169

【问题讨论】:

    标签: asp.net-mvc-3 jquery


    【解决方案1】:

    FormsAuthentication 在其 http 模块中有处理程序,它将所有 401 响应重定向到登录页面而不是错误页面。

    查看FormsAuthenticationModule 的源代码应该有(非常丑陋的)解决方法 - 如果您将ReturnUrl=/ 附加到您的查询字符串,该模块不应该进行重定向。

    最好的解决方案可能是编写自己的http模块进行身份验证-您可以在反射器中打开FormsAuthenticationModule并将其用作参考。

    【讨论】:

      猜你喜欢
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 2020-04-24
      • 2013-12-30
      • 1970-01-01
      相关资源
      最近更新 更多