jQuery AJAX 将重定向视为状态 200 而不是 302?

发布于 2024-08-01 21:29:53 字数 276 浏览 5 评论 0原文

我使用 jQuery 和 jQuery.form 插件来提交我的表单(也使用 ASP.Net MVC)。

问题是用户位于使用表单身份验证的网站部分,如果他们的身份验证 cookie 在页面上的时间内过期,而不是返回 302 状态(这将是重定向到登录页面),我仍然会得到 200 ?

在 FireBug 中,我看到 302 Found,然后我的登录页面接下来会显示 200,这是发送回我的 Ajax 调用的状态代码。 如果我从未看到 302 发送回 jQuery 表单插件,我如何检测他们已注销?

I am using jQuery and the jQuery.form plugin to submit my form (also using ASP.Net MVC).

Problem is the user is in a section of the site that uses forms authentication and if their auth cookie expires during their time on the page instead of getting back a status of 302, which would be the redirect to the login page, I still get 200?

In FireBug I see the 302 Found and then my login page is served next as a 200 which is the status code sent back to my Ajax call. How do I detect that they have been logged out if I never see the 302 sent back to the jQuery form plugin?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

成熟稳重的好男人 2024-08-08 21:29:53

我真的很喜欢这个解决方案。 通过将 ajax 请求上的 302 响应更改为 401,它允许您在客户端设置 ajax 来监视任何寻找 401 的 ajax 请求,如果找到则重定向到登录页面。 非常简单有效。

Global.asax:

protected void Application_EndRequest()
{
    if (Context.Response.StatusCode == 302 &&
        Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
    {
        Context.Response.Clear();
        Context.Response.StatusCode = 401;
    }
}

客户端代码:

 $(function () {
      $.ajaxSetup({
        statusCode: {
          401: function () {
            location.href = '/Logon.aspx?ReturnUrl=' + location.pathname;
          }
        }
      });
    });

I really like this solution. By changing the 302 response on ajax requests to a 401 it allows you to setup your ajax on the client side to monitor any ajax request looking for a 401 and if it finds one to redirect to the login page. Very simple and effective.

Global.asax:

protected void Application_EndRequest()
{
    if (Context.Response.StatusCode == 302 &&
        Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
    {
        Context.Response.Clear();
        Context.Response.StatusCode = 401;
    }
}

Client Side Code:

 $(function () {
      $.ajaxSetup({
        statusCode: {
          401: function () {
            location.href = '/Logon.aspx?ReturnUrl=' + location.pathname;
          }
        }
      });
    });
等风来 2024-08-08 21:29:53

尝试使用缓存: false jquery ajax 中的缓存选项

$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});

---编辑
尝试使用 C# 代码:

protected void Page_Load(object sender, System.EventArgs e)
{
   Response.Cache.SetCacheability(HttpCacheability.NoCache);
   ...
}

try with cache: false cache option in jquery ajax:

$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});

---EDIT
Try with this in C# code :

protected void Page_Load(object sender, System.EventArgs e)
{
   Response.Cache.SetCacheability(HttpCacheability.NoCache);
   ...
}
清浅ˋ旧时光 2024-08-08 21:29:53

以前也遇到过类似的问题。 此问题中给出的解决方案有帮助吗?

A similar problem has been encountered before. Is the solution given in this question helpful?

贵在坚持 2024-08-08 21:29:53

我很确定你永远不会在 XHR 对象的完成状态下得到 302。 如果发生重定向,则连接仍在进行中,直到您看到登录页面的响应(应为 200,如果存在)。

但是,为什么需要看到302呢? 当然,如果您重定向到 login.php,那么只需获取返回响应的 url(或解析内容)就可以告诉您他们已注销?

仅当您想知道会话何时过期(在执行某些操作之前)时,另一种选择是使用 setTimeout 或类似方法轮询服务器以获取有关身份验证状态的信息。

祝你好运。

I'm pretty sure you will never get the 302 in the completed status of the XHR object. If a redirect occurs then the connection is still in process until you see the response from the login page (which should be 200, if it exists).

However, why do you need to see the 302? Surely if you are getting a redirect to login.php then simply getting the url (or parsing for content) of the returned response tells you they have been logged out?

An alternative, only if you want to know as soon as the session has expired (before they do some action), is to poll the server using setTimeout or similar to get information on the authentication status.

Good luck.

清秋悲枫 2024-08-08 21:29:53

这是我过去使用过的解决方案:

服务器端:

当我检查会话是否仍然有效时,我还会留意“X-Requested-With”标头,它应该是“ XMLHttpRequest”如果您使用的是 jQuery(注意:IE 倾向于以小写形式返回标头名称,因此也要注意这一点)。 如果会话确实已过期并且标头存在,则我不使用 HTTP 重定向,而是使用一个简单的 JSON 对象进行响应,如下所示:

{ "SESSION": "EXPIRED" }

客户端:

在我的 onload 代码中,我使用 jQuery 的 ajaxComplete 事件来检查所有传入请求负载会话过期对象。 代码看起来像这样:

$(window).ajaxComplete(function(ev, xmlhr, options){
    try {
        var json = $.parseJSON(xmlhr.responseText);
    }
    catch(e) {
        console.log('Session OK');
        return;
    }

    if ($.isPlainObject(json) && json.SESSION == 'EXPIRED') {
        console.log('Session Expired');

        //inform the user and window.location them somewhere else

        return;
    }

    console.log('Session OK');
});

This is the solution I've used in the past:

Server side:

When I'm checking to see if a session is still valid, I also keep an eye out for the "X-Requested-With" header, which should be "XMLHttpRequest" if you're using jQuery (NOTE: IE tends to return the header name in lower case, so watch for that as well). If the session has indeed expired and the header is present, instead of using an HTTP redirect, I respond with a simple JSON object like this:

{ "SESSION": "EXPIRED" }

Client side:

In my onload code, I use jQuery's ajaxComplete event to check all incoming request payloads for the session expired object. The code looks something like this:

$(window).ajaxComplete(function(ev, xmlhr, options){
    try {
        var json = $.parseJSON(xmlhr.responseText);
    }
    catch(e) {
        console.log('Session OK');
        return;
    }

    if ($.isPlainObject(json) && json.SESSION == 'EXPIRED') {
        console.log('Session Expired');

        //inform the user and window.location them somewhere else

        return;
    }

    console.log('Session OK');
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文