当用户会话过期或请求在302中终止时,您如何处理AJAX请求 [英] How do you deal with AJAX requests when user session expires, or where the request terminates in a 302
问题描述
已经提出了其他类似的问题,但是它们并没有倾向于处理通用的多用途解决方案.他们倾向于只处理用户身份验证问题.有时302在其他情况下也有效.
Other questions similar have been asked, but they didnt tend to deal with a generic multi purpose solution. They tended to deal only with user authentication issues. Sometimes a 302 is valid for other circumstances.
那么您如何为ajax请求创建通用302处理程序,同时又为应用程序中的其他任何功能保持功能?
So how can you create a generic 302 handler for ajax requests, while maintaining functionality for anything else in your application?
推荐答案
我们最终提出的解决方案有些古怪,但看起来很优雅.
The solution we came up with in the end was a little hacky but seems quite elegant.
首先在global.asax文件中拦截来自ajax查询的任何302.
Start by intercepting any 302's that come from an ajax query in your global.asax file.
protected void Application_EndRequest()
{
var context = new HttpContextWrapper(Context);
if (Context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
{
Context.Response.Clear();
Context.Response.StatusCode = 308;
}
}
我们发明了状态代码308,以使浏览器不会拦截302并导致jquery失败.
We invented a status code of 308, so that the browser doesn't intercept the 302 and cause jquery to fail.
然后在您的javascript全局文件中的某处添加以下内容
And then somewhere in your javascript global file, add the following
$(document).ajaxError(function (e, request, errorThrown, exception) {
if (request.status == "308") {
window.location = request.getResponseHeader('location');
}
});
这会使jquery能够检测到重定向,然后将用户定向到请求的页面.
This causes jquery to be able to detect the redirect, and then direct the user to the requested page.
这篇关于当用户会话过期或请求在302中终止时,您如何处理AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!