ASP.NET - Javascript timeOut Warning based on sessionState timeOut in web.config

后端 未结 6 1611
囚心锁ツ
囚心锁ツ 2020-12-06 08:33

Problem: I am looking to create a time-out warning message on an asp.net page with a c# code behind based off my webconfig sessionState TimeOut Attribute.

Code on w

6条回答
  •  抹茶落季
    2020-12-06 09:30

    I've done this before by creating a web method in my code-behind file that checks for the timeout. Have your Javascript function get the timeout information via AJAX and display a warning according.

    Example

    This is the web method in my code-behind:

    [WebMethod]
    public static bool HasSessionTimedOut()
    {
        HttpSessionState session = HttpContext.Current.Session;
    
        // I put this value into Session at the beginning.
        DateTime? sessionStart = session[SessionKeys.SessionStart] as DateTime?;
    
        bool isTimeout = false;
    
        if (!sessionStart.HasValue)
        {
            isTimeout = true;
        }
        else
        {
            TimeSpan elapsed = DateTime.Now - sessionStart.Value;
            isTimeout = elapsed.TotalMinutes > session.Timeout;
        }
    
        return isTimeout;
    }
    

    And this is my Javascript:

     
    

    So, this is pretty rudimentary. Every 30 seconds, my Javascript function sends an AJAX request to my web method using ASP.NET's PageMethods object. It checks for a return value of true in the callback, which indicates that a timeout has occurred, and takes the appropriate action.

提交回复
热议问题