【问题标题】:session timeout on ajax callajax 调用会话超时
【发布时间】:2012-12-15 13:47:33
【问题描述】:

我知道这是重复的,但我无法获得可靠的解决方案(对于 asp.net web)。

如果会话到期,我只想重定向到登录页面。 我试过以下:

1。使用 jquery 状态码

    $.ajax({
     type: "POST",
     url: "stream.asmx/SomeMethod",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function (msg) {
        //success msg
     },
     error: function (request, status, error) {
        if (status = 403) {
            location.href = 'login.aspx';
        }
     }
    });

问题:这也会为其他错误返回相同的状态代码(403),我只希望会话超时。

2。发送 json 消息是否会话过期

后面的代码:

    if (!object.Equals(HttpContext.Current.Session["User"], null))
    {
        Id = int.Parse(HttpContext.Current.Session["User"].ToString());
    }
    else
    {
        result = from row in dtscrab.AsEnumerable()
                 select new
                 {
                     redirectUrl = "login.aspx",
                     isRedirect = true
                 };
    }

关于 $.ajax 成功:

    success: function (msg) {
        if (msg.d[0].isRedirect) {
            window.location.href = msg.d[0].redirectUrl;
        }
        else {
            //load containt
        }
     }

问题:如果会话过期(它确实返回正确的 json),它会以某种方式不调用 ajax 成功行。如果页面中有很多 ajax 请求(应该全局处理),即使这也不是正确的方法。

但是,我看到这篇文章确实是一个很好的解决方案,但它适用于使用 AuthorizeAttribute 的 mvc:handling-session-timeout-in-ajax-calls

那么,我可以在 asp.net web api 中使用 AuthorizeAttribute 来使用 mvc 中使用的相同概念吗?如果没有,我该如何解决我面临的那些问题(上述两个中的任何一个)?

【问题讨论】:

标签: c# asp.net ajax session session-timeout


【解决方案1】:

403 状态码将导致 jQuery 调用失败方法。在第二次尝试时保留相同的代码,但将重定向处理程序移动到失败方法而不是成功方法。在成功方法中,像平常一样对待它。

【讨论】:

    【解决方案2】:

    问题:

    我的 Razor MVC 应用程序在会话超时时进行 ajax 调用时抛出异常时遇到了同样的问题。

    我设法解决此问题的方法是通过使用简单的轻量级操作方法 (RAZOR MVC) 监视每个 ajax 请求,该方法返回一个布尔变量,无论请求是否经过身份验证。请在下面找到代码..

    布局/母版页/脚本文件:

    <script>
    var AuthenticationUrl = '/Home/GetRequestAuthentication';
    var RedirectUrl = '/Account/Logon';
    
    function SetAuthenticationURL(url) {
    AuthenticationUrl = url;
    }
    
    function RedirectToLoginPage() {
    window.location = RedirectUrl; 
    }
    
     $(document).ajaxStart(function () {
     $.ajax({
        url: AuthenticationUrl,
        type: "GET",
        success: function (result) {
            if (result == false) {
                alert("Your Session has expired.Please wait while redirecting you to login page.");
                setTimeout('RedirectToLoginPage()', 1000);
            }
        },
        error: function (data) { debugger; }
    });
    

    })

    然后在 Home Controller/Server 端你需要一个方法来验证请求并返回布尔变量..

        public ActionResult GetAuthentication ( )
        {
            return Json(Request.IsAuthenticated, JsonRequestBehavior.AllowGet);
        }
    

    这将验证每个 ajax 请求,如果会话因任何 ajax 请求而过期,它会通过消息提醒用户并将用户重定向到登录页面。

    我还建议不要使用标准的 Alert to Alert。使用一些工具提示类型的格式化 div 警报。标准 JS 警报可能会强制用户在重定向之前单击“确定”。

    希望对您有所帮助.. :)

    谢谢, 里亚兹

    【讨论】:

      【解决方案3】:

      最后,我终于跟上了。

      public class IsAuthorizedAttribute : ActionFilterAttribute
          {
              public override void OnActionExecuting(ActionExecutingContext filterContext)
              {
                  if (filterContext.HttpContext.Request.IsAjaxRequest())
                  {
                      var sessions = filterContext.HttpContext.Session;
                      if (sessions["User"] != null)
                      {
                          return;
                      }
                      else
                      {
                          filterContext.Result = new JsonResult
                          {
                              Data = new
                              {
                                  status = "401"
                              },
                              JsonRequestBehavior = JsonRequestBehavior.AllowGet
                          };
      
                          //xhr status code 401 to redirect
                          filterContext.HttpContext.Response.StatusCode = 401;
      
                          return;
                      }
                  }
      
                  var session = filterContext.HttpContext.Session;
                  if (session["User"] != null)
                      return;
      
                  //Redirect to login page.
                  var redirectTarget = new RouteValueDictionary { { "action", "LogOn" }, { "controller", "Account" } };
                  filterContext.Result = new RedirectToRouteResult(redirectTarget);
              }
          }
      

      处理客户端

      <script type="text/javascript">
          $(document).ajaxComplete(
             function (event, xhr, settings) {
                 if (xhr.status == 401) {
                     window.location.href = "/Account/LogOn";
                 }
          });
      </script>
      

      【讨论】:

        【解决方案4】:

        您可以设置会话超时过期警告,例如 ....

        <script type="text/javascript"> 
        
        //get a hold of the timers
        var iddleTimeoutWarning = null;
        var iddleTimeout = null;
        
        //this function will automatically be called by ASP.NET AJAX when page is loaded and partial postbacks complete
        function pageLoad() { 
        
            //clear out any old timers from previous postbacks
            if (iddleTimeoutWarning != null)
                clearTimeout(iddleTimeoutWarning);
            if (iddleTimeout != null)
                clearTimeout(iddleTimeout);
            //read time from web.config
            var millisecTimeOutWarning = <%= int.Parse(System.Configuration.ConfigurationManager.AppSettings["SessionTimeoutWarning"]) * 60 * 1000 %>;
            var millisecTimeOut = <%= int.Parse(System.Configuration.ConfigurationManager.AppSettings["SessionTimeout"]) * 60 * 1000 %>; 
        
            //set a timeout to display warning if user has been inactive
            iddleTimeoutWarning = setTimeout("DisplayIddleWarning()", millisecTimeOutWarning);
            iddleTimeout = setTimeout("TimeoutPage()", millisecTimeOut);
        } 
        
        function DisplayIddleWarning() {
            alert("Your session is about to expire due to inactivity.");
        } 
        
        function TimeoutPage() {
            //refresh page for this sample, we could redirect to another page that has code to clear out session variables
            location.reload();
        } 
        

        【讨论】:

        • 感谢 Manibhadra 的快速回复,但我正在寻找一种在客户端(在 ajax 调用上)查找会话超时的可靠方法。
        【解决方案5】:

        4xx 是 HTTP 错误状态码,会导致 jquery 执行 onFailure 回调。

        此外,当您想要处理有效负载时,请注意使用 3xx 进行重定向。根据我的经验,Internet Explorer 只会在返回 3xx 状态代码时进行重定向(不查看有效负载)。

        我会说,抛出 403 并处理这种情况。对于客户端 403 意味着资源访问被禁止。可能有多种原因,我想这没关系。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-10
          • 1970-01-01
          • 2011-07-11
          • 1970-01-01
          • 1970-01-01
          • 2017-12-30
          • 1970-01-01
          相关资源
          最近更新 更多