ASP.NET MVC迫使一个AJAX请求被重定向到登录页面时,FormsLogin会话不再有效 [英] ASP.NET MVC forces an AJAX request be redirected to the login page when the FormsLogin session is no longer active

查看:668
本文介绍了ASP.NET MVC迫使一个AJAX请求被重定向到登录页面时,FormsLogin会话不再有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使通过jQuery.AJAX方法PartialViewResults一些AJAX调用。这个伟大的工程,我得到我的观点呈现正是我想要的方式。

I have some AJAX calls that render PartialViewResults via the jQuery.AJAX method. This works great, I get my views rendered exactly the way I want.

当我离开这个页面了一段时间,并在窗体身份验证会话过期的问题就出现了。当我点击执行一个AJAX请求的动作,它显示在我的分区登录页面。

The problem arises when I leave the page up for a while and the Forms auth session expires. When I click an action that performs an AJAX request, it shows the login page in my div.

我想它的整个页面重定向到登录页面。

I want it to redirect the WHOLE page to the login page.

推荐答案

将它设置在Application_EndRequest()在Global.asax方法

Set it up in the Application_EndRequest() method of the Global.asax

您可以检查该请求是否是一个Ajax请求,并检查它是否正在发送一个HTTP重定向(302),如果是的话,我们在实际工作要发送401。

You can check to see if the request is an ajax request and also check if it is sending an HTTP redirect (302) if it is, then we actuall want to send a 401.

protected void Application_EndRequest() {
            var context = new HttpContextWrapper(Context);
            // If we're an ajax request, and doing a 302, then we actually need to do a 401
            if (Context.Response.StatusCode == 302 && context.Request.IsAjaxRequest()) {
                Context.Response.Clear();
                Context.Response.StatusCode = 401;
            }
        }

然后在您的客户端code,在全球访问的区域:

Then in your client code, in a globally accessible area:

MyNamespace.handleAjaxError = function (XMLHttpRequest, textStatus, errorThrown) {
    if (XMLHttpRequest.status == 401) {
        // perform a redirect to the login page since we're no longer authorized
        window.location.replace("logout path");
    }    
    } else {
        MyNamespace.displayGeneralError();
    }
};

  $.ajax({
  type: "GET",
  url: userAdmin.addUserActionUrl,
  success: userAdmin.createUserEditorDialog,
  error: MyNamespace.handleAjaxError
 });

这篇关于ASP.NET MVC迫使一个AJAX请求被重定向到登录页面时,FormsLogin会话不再有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆