jquery - 当 FormsLogin session 不再事件时,ASP.NET MVC 强制将 AJAX 请求重定向到登录页面

标签 jquery asp.net-mvc ajax session forms-authentication

我有一些 AJAX 调用,通过 jQuery.AJAX 方法呈现 PartialViewResults。这非常有效,我的 View 完全按照我想要的方式呈现。

当我将页面保留一段时间并且表单例份验证 session 过期时,就会出现问题。当我单击执行 AJAX 请求的操作时,它会在我的 div 中显示登录页面。

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

最佳答案

在 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
 });

关于jquery - 当 FormsLogin session 不再事件时,ASP.NET MVC 强制将 AJAX 请求重定向到登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3431343/

相关文章:

javascript - 调整大小功能加载页面

javascript - 将 jQuery 与 google.load 一起使用

c# - MiniProfiler 类型存在于 Miniprofiler.Shared 和 MiniProfiler 中

jQuery 追加获取 XHTML 结果失败

javascript - 在 JSONP 结果中设置 sessionStorage?

javascript - 要求用户先登录 - 网页

javascript - 如果宽度 > 915 像素,则使用函数滚动页面 100 像素

asp.net - Asp.NET 5 中的 HtmlEncode 在哪里

c# - 返回查看 ToList() 不工作

javascript - 从另一个域获取 html 内容时出错