Get ASP.NET Session Last Access Time (or Time-to-Timeout)

后端 未结 4 559
天涯浪人
天涯浪人 2020-12-18 17:44

I\'m trying to determine how much time is left in a given ASP.NET session until it times out.

If there is no readily available time-to-timeout value, I could also ca

4条回答
  •  情话喂你
    2020-12-18 18:10

    I have just implemented a solution like the one asked about here and it seems to work. I have an MVC application and have this code in my _Layout.chtml page but it could work in an asp.net app by placing it in the master page I would think. I am using local session storage via the amplify.js plugin. I use local session storage because as Mr Grieves says there could be a situation where a user is accessing the application in a way that does not cause a page refresh or redirect but still resets the session timeout on the server.

    $(document).ready(function () {
    
    var sessionTimeout = '@(Session.Timeout)'; //from server at startup
    amplify.store.sessionStorage("sessionTimeout", sessionTimeout);
    amplify.store.sessionStorage("timeLeft", sessionTimeout);
    setInterval(checkSession, 60000); // run checkSession this every 1 minute
        function checkSession() {
        var timeLeft = amplify.store.sessionStorage("timeLeft");
        timeLeft--; // decrement by 1 minute
        amplify.store.sessionStorage("timeLeft", timeLeft);
            if (timeLeft <= 10) {
            alert("You have  " + timeLeft + " minutes before session timeout. ");
                       }
         }
    });
    

    Then in a page where users never cause a page refresh but still hit the server thereby causing a reset of their session I put this on a button click event:

    $('#MyButton').click(function (e) {
    
       //Some Code that causes session reset but not page refresh here
        amplify.store.sessionStorage("sessionTimeout", 60); //default session timeout
        amplify.store.sessionStorage("timeLeft", 60);
    
    
    });
    

    Using local session storage allows my _Layout.chtml code to see that the session has been reset here even though a page never got refreshed or redirected.

提交回复
热议问题