.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

HTTPContext.Current.Session losing the variable sporatically

Posted By:      Posted Date: September 02, 2010    Points: 0   Category :ASP.Net
I have noticed a strange behaviour in my ASP.net 2.0 application. I have some logic in my aspx page that accesses some Session variables fine, then accesses some app_code and most of the time the HTTPContext.Current.Session returns the variable back fine.  However, I have noticed that sometimes this Session returns null, like it has lost it's "pointer" to the current HTTPContext. Is this a known bug, has anyone seen something like this before?   Any help would be appreciated, thanks, Mark. 

View Complete Post

More Related Resource Links


Hello, everyone! Well, I made some researches to discover how can I use session variables in App_code. A lot of sites show me answer is use HttpContext.Current.Session. But I´m having following error: The name 'HttpContext' does not exist in the current context. What can I do?

redirectMode="ResponseRewrite" disables HttpContext.Current.Session



we render a nice error page which uses quite a lot of code in the background. I tried adding redirectMode="ResponseRewrite" to the customErrors section in the web.config, but then the framework returns null from HttpContext.Current.Session. Therefore some of our code does not work anymore. When redirectMode is not set or set to ResponseRedirect then HttpContext.Current.Session is set.

How can we circumvent this?



HTTPContext.Current.Session is NULL in SharePoint 2007 (MOSS)


For some strange reason HTTPContext.Current.Session is null in SharePoint 2007 web application.

Session is enabled everywhere and used to work so its not a setup issue. Something got corrupted at some point either via patches or something...

Doing "Reset To Definition" fixes the issue, but I can't do that in production environment and what is reset to definition has to do with session being null?

Searching on the web found a post from someone having same exact issue:


I need to know how to FIX this w/o doing complete "Reset To Definition".

Are same the System.Web.HttpContext.Current.Session and normal Session?


Hi all,

I have used System.web.httpcontext.current.session and normal session in my web application

both sessions are having the same name.. but i can get the value from session["name"] not from System.web.httpcontext.current.session["name"]..

is there any problem..

I have used system.web.httpcontext.current.session in my class file..

session have use in my aspx.cs file..

supppose I need to check the session["name"] in my class file what should I do?

is there any diffreence between thease?



Users getting logged out because HttpContext.Current is null


We've  been trying to fix this one for a couple years, and I'm just out of ideas, so any help is really appreciated!

We've got a fairly large, complex web application that uses Forms Authentication to authenticate users.  Throughout the application we store and retrieve information about users in the Session object, and in some cases in cookies.  In a couple places we check for the existence of the context, and if it's null we send the user back to the login page to re-establish the session. 

Just a quick run-down of this web app: C#, .NET 3.5, IIS 6, ASP.NET State Service to manage session

As for the session timer, we use our own home-grown timer, which is basically a client-side timer, which is backed up by a check to the SQL database to see when their last activity was.  This seems to work well for us.  It's not perfect, but it allows us to notify the user before the session times out, and allows us to be certain we're not logging a user out before their 60 minutes of inactivity is up.

What's happening is that certain users are being logged out after just a few minutes.  We've eliminated the timer as a cause and believe what's happening is the HttpContext.Current is null, so the user is logged out.  We do not know why the HttpContext.Current is null, and I underst

Session Variable issues


Hello everyone,

I ran into an issud to day with the follwoing code.  The strPanelOrder session variable is false, however, once it goes into the next if statement and sets the strTrimOrder to True, it changes the strPanelOrder session varialbe to true as well.  Why is this and how to I stop that from happening?

If Session(strPanelOrder) Is "False" Then
                If (strItemNumber.Length() = 10) And (strItemNumber.Substring(0, 2) = "FS" Or strItemNumber.Substring(0, 2) = "FC" Or strItemNumber.Substring(0, 2) = "DS" Or strItemNumber.Substring(0, 2) = "DC") Then
                    Session(strPanelOrder) = "True"
                End If
End If
If Session(strTrimOrder) Is "False" Then
               If (strItemNumber.Substring(4, 1) = "T") And (strItemNumber.Substring(0, 2) <> "AC") And (strItemNumber <> "Length") Then
                    Session(strTrimOrder) = "True"
                End If
End If


Thanks in advance for taking a look at this.



How to store and retrieve multiple values in a single session variable .


I want to store employee name,designation and department in session variable and
retrieve in another page how to do this.

Textbox text populated by Session Variable wont update into SQL with new text


Hi everyone, I have what I think is a weird issue. I send text from one page to another via Session Variable. When page 2 loads, the text box has the session text set, but if the user changes the text and clicks the button, the SQL database is update with the original session text. If I remove the redirect from the page 2 button_Click method, then, the page refreshes with the textbox reverting to the session text and thr SQLDataSource has the session text added to it.

Why would the button click cause the textbox refresh with the text from the pageLoad before updating the data source?


Partial Class _1
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Session("UpdateProd") = "Have some text here to send to a textbox on page 2"
    End Sub
End Class

Partial Class _2
    Inherits System.Web.UI.Page


Retaining Datagrid Results using Session Variable


I have a page with 2 dropdown menus and 2 datagrids.
The datagrids get populated by a database based on a dropdown menu slection.

This page links to another page which in turn links back to the original.
If the user leaves the first page and then returns back I want to keep the dropdown menus and datagrids populated.

I tried doing this with session variables but can't get the datagrids to stay populated ...

    protected void btnSubmit_Click(object sender, EventArgs e)
        if (this.ddlName.SelectedIndex > 0)
            GridView1.Visible = true;
            GridView2.Visible = false;

            Session.Add("name", this.ddlName.SelectedValue);
            Session.Add("gridview1", GridView1.SelectedValue);

    protected void btnSubmit_Click1(object sender, EventArgs e)
        if (this.ddlLocation.SelectedIndex > 0)
            GridView2.Visible = true;
            GridView1.Visible = false;

            Session.Add("location", this.ddlLocation.SelectedValue);
            Session.Add("gridview2", GridView2.SelectedValue);

    protected override void Page_Load(object sender, EventArgs e)


Session variable in Javascript

Hi, I had tried to use a Session variable in Javascript which are placed in the Header html. but got no luck. In my Init function, I intended to read the username value from database and place it in the session variable["username"].Then the username can be utilized in the second line of code shown as below. <script type="text/javascript"> //load session variable into "username" here. Sys.Application.add_load(Init); </script> <script type="text/javascript" src="http://api.art.com/api?service=api&v=3.1.9&user=<%=(string)Session["username"]%>"></script>Here are the code inside the Init:function Init () { WebService.GetAuthentication(getAuthenticationOnSuccess, getAuthenticationOnFailed); } function getAuthentication() { WebService.GetAuthentication(getAuthenticationOnSuccess, getAuthenticationOnFailed); } function getAuthenticationOnSuccess(result, context) { if(result) { getQueryStringInfo(); } } function getAuthenticationOnFailed(error) { showError(error); } Please help.Cheers,  

query string or session variable or neither for this scenario?

Hello,example scenario: user login has a list of associated 'accounts' it has access to... this list of accounts is stored in a database table, say tblAccountAccessControl, something like:login, accountID-----------------------userA, account123userA, account456userA, account798userB, accountABCuserB, accountDEFetc..this info is used throughout the web application and determines the 'domain' of information the particular login has access to. For example there are many other tables that have the 'accountID' field and whenever a page pulls data from the table it only pulls data that the currently logged in user should be allowed to see, based on that tblAccountAccessControl data.the security question:1) do I need to query the database every time I need to get this list of allowed accountID's? I was about to use a plain old query string to pass a particular accountID to another page but quickly caught myself as I realized that would be a major security flaw (the receiving page was going to use that accountID to grab info from the database, and there would be nothing preventing a user from simply typing in a url manually to get data from an accountID they are not supposed to be allowed to view). So I then thought I'll just store the list of accountID's in a session state variable so they will be carried with the user throughout the sessi

Session Variable use / IsolatedStorage

I am using ASP.NET 2.0I am little bit confuse about using of Session Variable. I have a three page web application. When a user login, after verification of user credentials I get user ID from DB and store this ID in a session variable.Session("USERID") = 56by using this ID I can get 20 different values from database as User Full name, user date of birth, user location, user date of joining, User Commission rate  etc. I need some of these values in Page 1, some in page 2 and some values needed in Page 3My question is that what is the best method !01. After successfully login and getting the User ID, I take all these 20 values from Data Base and store these values in an ArrayList and store this ArrayList in a seesion and whenever I need to use any value I take these values from ArrayList which is save in Session variable.02. I only save the user ID in session variable and whenever needed any user preference data, by using this ID I run the sql query and get the data and use this.03. Can I take some benefit by using the IsolatedStorage for this purpose.


I am using Forms  Authentication. I set the cookie when user logs in. Welcome text =  HttpContext.Current.User.Identity.Name Logout = Session.Abandon and Session.Clear() Now when I logon using different user name i still see my previous login name when I do" HttpContext.Current.User.Identity.Name  

HttpContext.Current is null

I have an intermittent issue where HttpContext.Current is null.  I do have aspNetCompatibilityEnabled="True".  I can duplicate it by restarting the webservice and make the request.  The first request has the HttpContext.Current set to null but subsequent requests have the proper HttpContext.  I've done some tracing and the messages are exactly the same. What else is weird is that the HttpContext is NOT null in my global.asax but by the time it hits my custom UsernamePasswordValidator, it is set to null.   Any ideas on what i'm doing wrong? HttpRequest from tracing: <HttpRequest> <Method>POST</Method> <QueryString></QueryString> <WebHeaders> <Cache-Control>no-cache</Cache-Control> <Connection>Keep-Alive</Connection> <Content-Length>799</Content-Length> <Content-Type>text/xml; charset=utf-8</Content-Type> <Accept>*/*</Accept> <Accept-Encoding>identity</Accept-Encoding> <Host>mydomain.com</Host> <User-Agent>Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E; InfoPath.2)</User-Agent> <SOAPAction>"http://tempuri.org/ICategoryService/GetAvailablePickList"</SOAPAction> </WebHeaders> </Htt

getting Session Variable using Javascript

Hey Forumers,I have been trying to get this javascript to work, but it seems it doesn't display my image.<script type="text/javascript">function getAvatar(){    var currentUser = <%=Session("UserName")%>    $('himg_something').src = "~/ProfileImage/" + currentUser + "/avatar.jpg"}    </script>himg_somthing is the img tag as follows:<img id="himg_something" alt="Avatar" src="~/ProfileImage/Image1.bmp" onload="getAvatar()"/>What I am basically trying to achieve is to display the user's avatar based on the session variable in code behind, but I cannot seem to get it to work. Thanks in advanceZeph

How to watch content of Session variable

I was debugging my web project and faced a problem that I don't know how to watch content of hashtables or similar data structures.For example, I have assigned before that Session["errorMessage"]="Hewstone we have a problem here...". What is my actions in order to watch that string in watches list?

httpcontext.current.user.identity.isauthenticated always false

Dear, please help me, I create two pages, the first one is the login page with user name and password textboxes - (not asp login control) , when clicking login button I check the login authentication, if it is true redirect to default page. in the default page if !IsCallBack then i check httpcontext.current.user.identity.isauthenticated if it is false i redirect the user to the login page. but my problem is that the httpcontext.current.user.identity.isauthenticated is always false. Below the section of authentication in web config < <authentication mode="Forms">forms loginUrl ="FrmUserLogin.aspx"  protection ="All"  timeout ="1"  name ="LoginRedirectCallback"  path ="/LoginRedirectCallback"  requireSSL ="false"  slidingExpiration ="true"  defaultUrl ="FrmDBLoginConfigaspx.aspx"  cookieless ="UseDeviceProfile"   < < </   </ </enableCrossAppRedirects ="false">credentials passwordFormat="Clear">user name ="admin" password ="admin"/>credentials>forms>authentication> thank you for any help.   Best Regards,
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend