当FormsLogin会话不再处于活动状态时,ASP.NET MVC强制将AJAX请求重定向到登录页面

我有一些AJAX调用通过jQuery.AJAX方法呈现PartialViewResults。 这很好用,我的视图完全按照我想要的方式呈现。

当我离开页面一段时间并且Forms身份validation会话到期时,会出现问题。 当我单击执行AJAX请求的操作时,它会在我的div中显示登录页面。

我希望它将WHOLE页面重定向到登录页面。

在Global.asax的Application_EndRequest()方法中进行设置

您可以检查请求是否是ajax请求,并检查它是否正在发送HTTP重定向(302),如果是,那么我们实际上想要发送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; } } 

然后在您的客户端代码中,在全局可访问的区域中:

 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,可以更轻松地解决此问题: Response.SuppressFormsAuthenticationRedirect

您可以在Global.asax.cs应用它:

 protected void Application_BeginRequest(object sender, EventArgs e) { HttpContextWrapper context = new HttpContextWrapper(this.Context); if (context.Request.IsAjaxRequest()) { context.Response.SuppressFormsAuthenticationRedirect = true; } } 

当我有FormsAuthentication时,我会在@Chris Kooken提供的答案https://stackoverflow.com/a/3431350/1559213中包含登录URL

 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.RedirectLocation.Contains(FormsAuthentication.LoginUrl)) { Context.Response.Clear(); Context.Response.StatusCode = 401; } }