Wednesday, September 14, 2016

Redirect to login page when session state time out is completed in asp.NET MVC


If you are working in asp.NET and need your application to redirect users to login page when session timeout is completed, you just need to implement 3 simple steps, and today is your lucky day because I'll show you how to do it...

1. Set the session timeout:
In AccountController.cs find you login method and find where SignStatus is success and place this line:

Session.Timeout = 20;  //put any number, remember this is in minutes

2. Script in _Layout.cshtml
In your Shared folder, open _Layout.cshtml and place this code:

<script>
    //session end 
    var sessionTimeoutWarning = @Session.Timeout- 1;

    var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
    setTimeout('SessionEnd()', sTimeout);

    function SessionEnd() {
        document.getElementById('logoutForm').submit();
    }
</script>
What we are doing here is is just calling SessionEnd() method 1 minute before session expires.


As you see, we just need a few steps to perform this event. It is recommended to set a timeout for our apps because increase security, but of course, all depends on kind of project we are working on

No comments:

Post a Comment