session variables lost for some reason

27,893

Solution 1

Sounds like your appdomain is being recycled. Is your web.config compilation element set in debug mode? In debug mode, ASP.NET resets the appdomain every 15 dynamic compilations. When that happens, if your sessions are stored in memory (InProc mode - the default), they'll be lost.

FYI, a dynamic compilation will occur whenever a file change happens on your site, like you editing an ASPX file, or an image being generated, or a web.config change.

So either put the site into Release mode (<compilation debug="false" ... />), or increase the numRecompilesBeforeAppRestart value from 15 in web.config, or use a non-volatile session storage mode - e.g. SQL Session State.

Solution 2

you will be surprised to know the behind the scene the session uses the cache!

have a look at the below(you will find all the common problem about session issue):

http://mmtripathi.blogspot.com/2008/09/session-lost-problem-after.html

http://zeeshanumardotnet.blogspot.com/2009/07/why-sessions-are-terminatedloss.html

http://classicasp.aspfaq.com/general/why-won-t-my-session-variables-stick.html

Solution 3

Are you losing just that particular variable? - If so, then it is probably some part of your code that is doing this.

If you are losing the entire session object, then unless your session has timed out, the other reason is that if you are using inproc session state at your server and ran out of memory - this recycles your worker process causing you to lose the session value. Check your event log to see if this is the case.

Solution 4

mesut:

Honestly Session memory can be very volitile. If the application goes down you can loose it, or like you said, if the user's session gets restarted you can loose it. Generally the options for Asp.Net are to store data in:

  • ViewState (stored as encrypted text accessable by your code-behind)

  • Session Memory (essentially a dictionary, but as above, a little
    volatile)

  • ASP.Net's State Service (which stores the values in a separate process. watch out for server farm scenarios)

  • Cookies

  • Cache

  • Url Parameters

Each of these methods has a trade-off in terms of performance, memory, or being dependent on a user's environment. I would try a different method and see if that is more robust for you.

Share:
27,893
ethem
Author by

ethem

Updated on July 26, 2020

Comments

  • ethem
    ethem almost 4 years

    I try to setup a E-shop. Next to every item I've an asp:imagebutton when this imagebutton is clicked I'm checking whehter the session varialbe session["basket"] exists or not if not then I add the values in a list (entity class) and I add this list in the session.

    if the session is not empty then I retrieve the values from session into List and change the list and then add the list back to session.

    Issue:

    For some reason I loose the session variable, suddenly. I checked on my watch (time) and it's unpredicatble sometimes it takes less than 1 minute, sometimes 3 minutes and sometimes 5 minutes etc....

    why do I loose the session variable?

    I googled and I've found - it can happen if you use Response.Redirect - w/o false parameter, or if you're in an UpdatePanel etc.

    I'm loosing the variable in the same page for the moment.

    The whole idea is put in a session variable and do checkout and retrieve the session variable in second aspx page... but this is not always working, because most of the case the session variables becomes empty. And sometimes it works.

    can someone advice ? what and where do I need to check? In some website pages (google) they advice to use caching, but caching is application based, so everybody will retrieve the same value.

    In my page any user (authenticated or anynomous user) in other words any user without login should able to order (I'll send invoice to pay upfront)....

    I''m not using webfarm, nor web garden... I just checked the IIS - website - session state - It's in process, cookie settings = use cookies, name = asp.net_sessionid, time-out = 20....

    please advice?

    It's C#, ASPX 3.5, IIS7.5

    I DON't have PAGE_LOAD in my ASPX page.

    // the only place I put the sessoin=null is a linkbutton, for the rest I don't put null in session["basket"]....

    protected void lnkDeleteAllSelected_Click(object sender, EventArgs e)
        {
            Session["Basket"] = null;
            ReloadBasketItems();
    
        }
    
     protected override void OnInit(EventArgs e)
        {
    
            base.OnInit(e);
            //System.Diagnostics.Debugger.Break();
    
            lvJuridisch.ItemDataBound += new EventHandler<ListViewItemEventArgs>(this.lv_ItemDataBound);
            lvJuridisch.DataBound += new EventHandler(lv_DataBound);
    
        }
    

    imgButtonAddtoBasket -> is defined as asp:imagebutton in the asp:listview

     protected void imgButtonAddtoBasket_Click(object sender, ImageClickEventArgs e)
        {
            ListViewDataItem lvi = ((sender as ImageButton).NamingContainer) as ListViewDataItem;
            DataKey currentDataKey = (lvi.NamingContainer as ListView).DataKeys[lvi.DataItemIndex];
            WebShopInfo SingleItem = new WebShopInfo();
            SingleItem.cd_type_pub = currentDataKey[0].ToString();
            SingleItem.no_pub = currentDataKey[1].ToString();
            SingleItem.no_suite_pub = Convert.ToInt32(currentDataKey[2]);
            SingleItem.cd_langue = Convert.ToChar(currentDataKey[3]);
            SingleItem.lb_titre_red = (lvi.FindControl("HiddenfieldProductRed") as HiddenField).Value;
    
            SingleItem.m_price = Convert.ToDecimal((lvi.FindControl("hiddenField_M_Price") as HiddenField).Value);
            SingleItem.nm_price = Convert.ToDecimal((lvi.FindControl("hiddenField_NM_Price") as HiddenField).Value);
            SingleItem.mt_pourc_tva = Convert.ToDecimal((lvi.FindControl("hfBTW") as HiddenField).Value);
    
    
            List<WebShopInfo> lws = new List<WebShopInfo>();
            if (Session["Basket"] == null)
            {
    
                //Session is empty so add listview to the session....
                //Session.Timeout = 20;  -- I tried this but this is not working too...
                lws.Add(SingleItem);
                Session["Basket"] = lws;
            }
            else
            {
                //Session is not empty so get asp:listview from the session.
                lws = Session["Basket"] as List<WebShopInfo>;
    
                WebShopInfo wsi = lws.Where(a => a.cd_type_pub == SingleItem.cd_type_pub &&
                                                a.no_pub == SingleItem.no_pub &&
                                                a.no_suite_pub == SingleItem.no_suite_pub &&
                                                a.cd_langue == SingleItem.cd_langue).SingleOrDefault<WebShopInfo>();
                if (wsi != null)
                    lws.Remove(wsi);
    
                if (SingleItem.Count > 0)
                    lws.Add(SingleItem);
                Session["Basket"] = lws;
            }
    
            ReloadBasketItems();
        }
    
  • Massimiliano Peluso
    Massimiliano Peluso almost 13 years
    yeah but most of the issue are common
  • ethem
    ethem almost 13 years
    The user selects the item and in postback I catch the selected item and put in as list then in a session, to keep the values after postback: I put in session because I need the value in another page.... but the session variable is lost in the same page
  • ethem
    ethem almost 13 years
    I'not using webfarm, nor web garden... I just checked the IIS - website - session state - It's in process, cookie settings = use cookies, name = asp.net_sessionid, time-out = 20.... Where can I see in the log: I looked at eventviewer - administratrive events -> can't find here info... where do I need to check? which log?
  • James McCormack
    James McCormack almost 13 years
    You didn't mention SQL State, which is my preferred method.
  • sll
    sll almost 13 years
    @mesut: Are you experiencing any errors on the Application_Error() level?
  • ethem
    ethem almost 13 years
    this is dotnetnuke CMS system... I think I don't have application_error -- but I'll try protected override void OnError(EventArgs e) { base.OnError(e); lblMessage.Text = e.ToString(); }
  • ethem
    ethem almost 13 years
    ok let me try Release mode.... but I can't find the word numberOfCompilations in web.config.
  • James McCormack
    James McCormack almost 13 years
    Sorry, it should be numRecompilesBeforeAppRestart. See here for more info: msdn.microsoft.com/en-us/library/s10awwz0.aspx
  • ethem
    ethem almost 13 years
    I try to apply sql Server session state: I get "Unable to use SQL Server because ASP.NET version 2.0 Session State is not installed on the SQL server. Please install ASP.NET Session State SQL Server version 2.0 or above. " I checked my Database and I see the necessary tables are created like aspnet_XXXX etc.. what could be the problem?
  • sll
    sll almost 13 years
    Tou should ask admins to install it
  • davecoulter
    davecoulter almost 13 years
    @James McCormack -- Ah yeah, totally.
  • Axelle
    Axelle almost 4 years
    I'm just wondering, what in code could be causing it? I currently have the same issue, but only some variables get lost. I never reassign the value inside the variable, but I do use the variable a lot.