在MVC Forms身份验证中处理未经身份验证的ajax请求

时间:2016-07-19 14:00:27

标签: c# asp.net-mvc-4

我有一个带有Forms身份验证的MVC 4.0网站,我正在尝试处理身份验证超时。具体来说,我需要在超时之后以不同于常规请求的方式处理ajax个请求,因为如果留给自己的设备,MVC的表单身份验证系统将发送302 FoundRedirect)到登录页面作为对ajax请求的响应...这结束时ajax调用接收到200 Success HttpStatusCode,这显然不是我想要发送的内容!

如何处理未经身份验证的ajax请求?

当然,扩展AuthorizeAttribute不是答案,因为授权仅在身份验证之后进入。在这种情况下永远不会调用HandleUnauthorizedRequestas opposed to the different answers in the question
我可以拦截global.asax中的每个请求并在那里查看...但这似乎是错误的方法。

我的web.config中的授权设置如下:

<authentication mode="Forms">
  <forms loginUrl="Login"
         protection="All"
         timeout="60"
         name=".ASPXAUTH"
         path="/"
         requireSSL="false"
         slidingExpiration="true"
         defaultUrl="Main"
         cookieless="UseDeviceProfile"
         enableCrossAppRedirects="false" />
</authentication>

<authorization>
  <deny users="?" />
</authorization>

<sessionState mode="InProc" timeout="60"></sessionState>

1 个答案:

答案 0 :(得分:0)

所以,我最终做的是允许web.config中的所有用户:

<authorization>
    <allow users="*" />
</authorization>

然后检查我自己的代码是否验证了用户...
必须有一个更好的方法,不是吗?