C# .NET - How to clear a session variable?

Asked By Daniel
18-Oct-11 06:15 PM
Hi!I have a [loginstatus] to my form but when a session is logged out It still keep its name in a label.how can I clear it once is logged out?I am using the following code:
 protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Mynumtel"] != null)
            {
                LabelAgentName.Text = GetAgentFunction(Session["Mynumtel"].ToString());
                LoginStatusA.LoginText = "Log out";
            }
            else
            {
                LoginStatusA.LoginText = "Log in";
            }
        }

  Adam replied to Daniel
18-Oct-11 06:18 PM
Session.Remove("Mynumtel");  

That should clear that session variable.
  Daniel replied to Adam
18-Oct-11 06:20 PM
Hi Adam!I wanted to say a [loginstatus].sorry for the title!!
  Adam replied to Daniel
18-Oct-11 06:23 PM
So is the problem the label just keeps the text?  If so, upon logout set Label.Text = String.Empty;  Just clear the value of it.
  Daniel replied to Adam
18-Oct-11 06:34 PM
Hi!when adding the LabelAgentName.Text = String.Empty to my code I am not able to see the text of  the person once is logged in.see how I done that:
 protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Mynumtel"] != null)
            {
                LabelAgentName.Text = GetAgentFunction(Session["Mynumtel"].ToString());
                LoginStatusA.LoginText = "Log out";
                LabelAgentName.Text = String.Empty;
            }
            else
            {
                LoginStatusA.LoginText = "Log in";
            }
        }
  Adam replied to Daniel
18-Oct-11 06:42 PM
I think I am understanding what you are trying to accomplish.

Try 

protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Mynumtel"] != null)
            {
                LabelAgentName.Text = GetAgentFunction(Session["Mynumtel"].ToString());
                LoginStatusA.LoginText = "Log out";
            }
            else
            {
                LabelAgentName.Text = String.Empty;
                LoginStatusA.LoginText = "Log in";
            }
        }

If that doesn't work try to explain the order in which things are happening in more detail, I think I am just not understanding the order.
  Daniel replied to Adam
18-Oct-11 07:07 PM
It is not working.the order is [label] then [loginstatus]
  Web Star replied to Daniel
18-Oct-11 11:47 PM
Simply use 
Session.Abandon(); // destroys the session and the Session_OnEnd event is triggered.

Session.Clear();  // just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want him to relogin for example) and reset all his session specific data.
  Suchit shah replied to Daniel
19-Oct-11 02:14 AM
Session.Abandon() 

http://msdn.microsoft.com/en-us/library/ms524310.aspx

Here is a little more detail on the HttpSessionState object:

http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate_members.aspx


Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want him to relogin for example) and reset all his session specific data.

  dipa ahuja replied to Daniel
19-Oct-11 04:05 AM
If you are using the Login status control You don't need to do this manually and because we use the Login control with it you can set the property directly in the markup page:

Take the Login View control and put the login Status inside it:

<%--<b>Login View</b>--%>
<asp:LoginView ID="LoginView3" runat="server">
<LoggedInTemplate>
  <asp:LinkButton ID="LinkButton3" runat="server" Text="My Profile" PostBackUrl="#" /><br />
  <asp:LoginStatus LogoutText="Sign Out" ID="LoginStatus" runat="server" />    
</LoggedInTemplate>      
<AnonymousTemplate>
<asp:LinkButton ID="lnk" runat="server" Text="Login" PostBackUrl="Login.aspx" /><br />
</AnonymousTemplate>
</asp:LoginView>
Create New Account
help
know the pblm session values are not found in another pages , i include a master page in my application, Give me a Solutions. . . Check your code in debug mode when you set the session and want to access that one on another page i think may be some where you reset it in your code. otherwise that should be available on another page . Also check the session time should not set 0 anywhere Hi, Below is some pseudo code for session expiration implementation Session expiration and how to redirect to the login page. However, most of the methods described require page refreshes or requests to the server to find out whether the session expired. Some ways browser + expired session". Below is sample code that will redirect the user to an expired page if the session has expired. void Session_OnStart(Object sender, EventArgs e) { HttpContext context = HttpContext.Current; HttpCookieCollection cookies = context.Request.Cookies; if (cookies[ "starttime" ] = = null ) { HttpCookie context.Response.Cookies.Add(cookie); } else { context.Response.Redirect( "expired.aspx" ); } } 2. The ASP.NET HttpSessionState class provides a useful IsNewSession( ) method that returns true if a new session was created
is User and other one is officer). ques is how to open the employee profile page after clicking on the login page. i have session variable see it. protected void btnLogin_Click( object sender, EventArgs e) { if (DDRole.SelectedValue = = "User" ) { Session[ "userType" ] = "User" ; } else { Session[ "userType" ] = "Officer" ; } } Hope you've already set Session variables for userId too. Our requirement is to transfer the page flow to user profile page (say profile.aspx). Once user clicks Login button in the login page, redirect them to the Profile.aspx page, in Profile.aspx page load, check the type of the user using session and load it accordingly. Hi, try
by writing into URL than how to restrict him and take him to the login page and after login take the user to that page for which he / she was looking. Thanks Hi There are three ways of approaching this create your own GUID and put it in the session object, void Session_Start( object sender, EventArgs e) { / / Code that runs when a new session is started Session["CustomSessionId"] = Guid .NewGuid(); } Second , BasePage.cs which would have inherited Page, in PageLoad() event, check whether the Session["CustomSessionId"] = = null, if it IS null, it means in the BasePage class so that it applies across the application. protected override void OnInit( EventArgs e) { base .OnInit(e); if (Context.Session ! = null ) { / / check whether a new session was generated htm"); Session[ "IsSessionTimeOut" ] = true ; } } } } } WARNING :- We will have to wireup the " void Session_Start( object sender, EventArgs e) " method in the Global.asax to use the Session.IsNewSession meaningfully. ASP.NET 2 period. Session_End happens on the server automatically regardless of whether a user has requested a page, so the idea of using it to do anything other than cleanup-type operations is a mistake; it is independent of the page lifecycle and there is no active Request or Response object to access there. It is
timer protected void Page_Load(object sender, EventArgs e) { mytimer.Elapsed + = new ElapsedEventHandler(ClosePage); mytimer.Interval = 10000; mytimer.Enabled = true; Console.ReadLine(); GC mytimer.Enabled = false; / / Environment.Exit(0); / / Response.Redirect("Default2.aspx"); / / i want to redirect next page. . . . . . } Server.Transfer("Webformpage.aspx"); or REsponse.Redirect("Webform.aspx"); To move to another webpage. Hi are a number of ways to redirect pages, such as the following: * By configuring the page to post to another page In this scenario, the user clicks a button that you have configured to post to a different page. This scenario is useful for multi-page forms. However, it requires user interaction. For details, see Cross Page Posting in ASP.NET Web Pages. * By dynamically using the browser In this scenario, you a command to the user's browser that causes the browser to retrieve a different page. This allows you to programmatically redirect to another page. However, the redirection causes a new
display a message when the session gets timed out. thanks in advance. The ASP.NET HttpSessionState class provides a useful IsNewSession( ) method that returns true if a new session was created implement this effectively for an entire web site, it is useful to utilize the “Base Page” concept described in a previous article . basePageSessionExpire.cs public class basePageSessionExpire : System.Web.UI.Page { public basePageSessionExpire() { } override protected void OnInit(EventArgs e) { base .OnInit(e); / / It appears from testing that the Request and Response both share actually sent by the agent with the request using the collection. Check if / / the given page supports session or not (this tested as reliable indicator / / if EnableSessionState is true), should not care about a page that does / / not need session if (Context.Session ! = null ) { / / Tested and the IsNewSession is more szCookieHeader.IndexOf( "ASP.NET_SessionId" ) > = 0)) { Response.Redirect( "sessionTimeout.htm" ); } } } } } sessionTimeout.htm This can be any page on the site, example just redirects to this page so just show a simple "A timeout has occurred" message for this article. Each other