Wednesday, 6 May 2015

Automatically redirect User after Session Timeout in ASP.Net


In this article I will explain how to automatically redirect User after Session Timeout in ASP.Net using C# and VB.Net.
When Session is timed out, user will be automatically redirected to the Login page.
 
Web.Config
The Session Timeout has been set to one minute for this article.
<sessionState timeout = "1"/>
 
 
HTML Markup
The HTML Markup consists of an ASP.Net AJAX Modal Popup along with its associated Panel control and two HTML SPAN elements to display the Session Timeout counter value.
For the Modal Popup I have specified
1. An OnOkScript event handler which will make call to a JavaScript function named ResetSession when the Yes button is clicked.
2. BehaviourID to access the Modal Popup using JavaScript.
3. Two Buttons i.e. Yes and No one being set as the OkControlID while other the CancelControlID respectively.
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<h3>Session Idle:&nbsp;<span id="secondsIdle"></span>&nbsp;seconds.</h3>
<asp:LinkButton ID="lnkFake" runat="server" />
<asp:ModalPopupExtender ID="mpeTimeout" BehaviorID ="mpeTimeout" runat="server" PopupControlID="pnlPopup" TargetControlID="lnkFake"
    OkControlID="btnYes" CancelControlID="btnNo" BackgroundCssClass="modalBackground" OnOkScript = "ResetSession()">
</asp:ModalPopupExtender>
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none">
    <div class="header">
        Session Expiring!
    </div>
    <div class="body">
        Your Session will expire in&nbsp;<span id="seconds"></span>&nbsp;seconds.<br />
        Do you want to reset?
    </div>
    <div class="footer" align="right">
        <asp:Button ID="btnYes" runat="server" Text="Yes" CssClass="yes" />
        <asp:Button ID="btnNo" runat="server" Text="No" CssClass="no" />
    </div>
</asp:Panel>
 
Note: To know the details related to the Look and Feel of the Modal Popup please refer my article ASP.Net AJAX Modal Popup with Rounded Corners using CSS3
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Configuration;
using System.Web.Configuration;
 
VB.Net
Imports System.Configuration
Imports System.Web.Configuration
 
 
Determining the Session Timeout from the Web.Config file
The following code gets the value of Session Timeout from the Web.Config file and then passes it to the SessionAlert JavaScript function which is called using the ClientScript function.
C#
protected void Page_Load(object sender, EventArgs e)
{
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    if (!this.IsPostBack)
    {
        Session["Reset"] = true;
        Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
        SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
        int timeout = (int)section.Timeout.TotalMinutes * 1000 * 60;
        ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert""SessionExpireAlert(" + timeout + ");"true);
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    If Not Me.IsPostBack Then
        Session("Reset") = True
        Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration("~/Web.Config")
        Dim section As SessionStateSection = DirectCast(config.GetSection("system.web/sessionState"), SessionStateSection)
        Dim timeout As Integer = CInt(section.Timeout.TotalMinutes) * 1000 * 60
        ClientScript.RegisterStartupScript(Me.GetType(), "SessionAlert""SessionExpireAlert(" & timeout & ");"True)
    End If
End Sub
 
 
Client Side Scripting
Following is the function which accepts the Session Timeout value from server side and then displays a Session Timeout counter. When there’s 20 seconds left for Session Timeout the AJAX Modal Popup is displayed.
If the user clicks Yes button inside the Modal Popup, the page is redirected and the Session is refreshed and if the user clicks No then simply the Modal Popup closes.
As soon as the Session expires, user is redirected to the Session Expired page.
<script type="text/javascript">
function SessionExpireAlert(timeout) {
    var seconds = timeout / 1000;
    document.getElementsByName("secondsIdle").innerHTML = seconds;
    document.getElementsByName("seconds").innerHTML = seconds;
    setInterval(function () {
        seconds--;
        document.getElementById("seconds").innerHTML = seconds;
        document.getElementById("secondsIdle").innerHTML = seconds;
    }, 1000);
    setTimeout(function () {
        //Show Popup before 20 seconds of timeout.
        $find("mpeTimeout").show();
    }, timeout - 20 * 1000);
    setTimeout(function () {
        window.location = "Expired.aspx";
    }, timeout);
};
function ResetSession() {
    //Redirect to refresh Session.
    window.location = window.location.href;
}
</script>
 
Display Session Timeout message before Session expires in ASP.Net

No comments:

Post a Comment