Search code examples
c#asp.netsessionweb-user-controls

how to clear session variable after a user control unload


i am using a session variable in a usercontrol (ascx), how can i remove that from session when user close webpage or redirect to other pages?


Solution

  • For redirect you can use this code when redirected page/view loaded:

    if (!IsPostBack)
    {
       Session.Clear(); //if you want clear session
       Session.Remove("myVar");//if you want clear just 1 session variable
    }
    

    With closing the page situation is harder, because HTTP is a stateless protocol, so you server does not know if user closed their browser or they just simply left an opened browser window for long time.

    Уou can use Ajax to handle clear session on tab close like below.

     <body onunload="unlodFunc()">
    
        <script>
        function unlodFunc()
        {
          $.ajax({
            type: "POST",
            url: "MyPage.aspx/ClearSession",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
    
            }
        });
        }
        </script>
    

    C# code:

    [WebMethod]
    public static void ClearSession()
    {
        if (Session["myVar"] != null)
        {
            Session.Remove("myVar");
        }
    }
    

    Also you can check this link.