我有一个使用表单身份验证用 asp.net mvc 编写的后端服务器.当用户未通过身份验证时,服务器会自动发送 302 重定向到登录操作并返回登录页面.
I have a back-end server written in asp.net mvc using Forms Authentication. When the user is not authenticated, the server will automatically send a 302 redirect to a Login action and return a Login page.
在客户端,我有一个项目列表.此列表仅供经过身份验证的用户访问.在页面上,我有一个使用 Ajax(jQuery 的 $.ajax 函数)刷新列表的按钮.
On client side, I have a list of items. This list is only accessible to authenticated users. On the page, I have a button to Refresh the list using Ajax ($.ajax function of jQuery).
现在,我的问题是当身份验证票超时并且用户单击刷新按钮时:
Now, my problem is when the authentication ticket is timeout and the user clicks on the Refresh button:
我想要的是当身份验证票超时并且用户单击刷新按钮时,我应该能够检测到并显示一条消息要求用户登录.
What I want is when the authentication ticket is timeout and the user clicks on the Refresh button, I should be able to detect that and display a message asking the user to Login.
我尝试通过在登录操作中添加自定义标头 (IS_LOGIN) 并在我的 ajax 响应中检查它来解决此问题.但这不是一个好的解决方案.
I tried to workaround this by adding a custom header (IS_LOGIN) in the Login action and check that in my ajax response. But it is not a good solution.
所以我的问题是:
感谢您的任何回复.
当调用是 XHR 时,不应重定向调用,而是使用 401 Unauthorized
响应并在回调中处理此问题.我不知道 ASP.NET,但我对 Spring Security 做了类似的事情.
You shouldn't redirect the call when it's an XHR but respond with a 401 Unauthorized
and handle this in your callbacks. I don't know ASP.NET but I did something similar with Spring Security.
概念如下:
X-Requested-With: XMLHttpRequest
401 Unauthorized
底线是,在某些情况下,XHR 调用需要与其他 HTTP 请求不同的处理方式.如果相同的资源位于另一个位置,您应该只重定向 XHR.
The bottom line is that XHR calls need to be handled differently then other HTTP requests in some cases. You should only redirect a XHR if the same resource is at another location.
您无法使用 XHR 回调处理重定向,因为浏览器会自动处理它们.您只会取回重定向位置的内容.
You can't handle redirects with XHR callbacks because the browser takes care of them automatically. You will only get back what at the redirected location.
这篇关于无法在 ajax 中处理 302 重定向,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!