'System.Web.HttpContext.Current.Session' is null - asp.net

I have an ASP.NET website that has been deployed since 2008 with plenty of users. From time to time, I've made updates to the site and uploaded those changes to the server without problems.
However, today, I'm trying to run the site on my development environment and I keep getting errors any time the code tries to access session state. It appears System.Web.HttpContext.Current.Session is always null!
Any suggestions on where to look? It's been a while since I worked on it and am not 100% sure if I've worked on it with the current version of ASP.NET (4.0).
Other than that, the code's been working fine and I haven't made any changes since it was last working.
More Information
I've spent all morning on this but I apparently have a larger issue.
If I step through the code, I see that my page Load handler executes. At this point, Session is not null. After that, my specialized master page executes. After that, my general master page executes. I then step through load events for a couple of controls. This all seems very normal.
Then, if I keep executing, suddenly I'm loading a specialized master page for another page and Session is now null!
If I hit F5, it the original page shows. But somehow it is causing the other page to load and without session state. If I turn off debug mode, it appears to run normally.
Obviously, I have something strange happening. I need to determine why the other page is being loaded.

Try to put a static page, something like Test.aspx and browse to that page. If it gets loaded, try to use Session property of the page in code behind. Do you still get the error? In that case, Session doesn't load. I suggest creating an HTTP Module and hooking into a method which is responsible for loading Session info. See what's wrong.

Just a guess - did you deactivate sessionState for any reason? Anything like this:
<sessionState mode="Off"/>

My apologies. The information I provided was completely misguided and was not sufficient to resolve the issue.
The problem was actually due to some custom error handling that redirected to an error page. This was configured in web.config. This error page was using the master page that my code was mysteriously executing.
Apparently, an error was occurring within the GridView control. This is ASP.NET code and not my own, so I was unable to step through it or catch it with a regular handler.
This was hard to understand. If I was executing the Load event handler of my error page, then it would've been obvious. But it appears to have skipped over that. Thus, my confusion.

Try checking the global.asax file or any other pre-load events and make sure the Session is not set to NULL explicitly.

Maybe your erring master page is calling code from some external class where the session object is not available?

Related

What happened to my ASP.NET website causing NullReferenceException in code behind on controls from MasterPage?

I have the strangest problem! I have an ASP.NET website application (luckily not yet live). Yesterday and everyday before, I could run the application without error. It was working fine when I turned the computer off late last night. When I ran the application today, I got a strange message telling me that my website was offline and that I should remove the app_offline.htm page from my root directory to put it back online.
I have never seen this message or page before, so I searched online to find that apparently SQL Server can put it there temporarily while it's busy to stop any more incoming requests (or something similar). Its proper use is to stop requests going to your site when you are updrading or doing maintenance. I proceeded to remove it as suggested. I cleaned and built the solution and then tried to run it. It no longer runs.
Now, I get an error in my MasterPage code behind where I normally access the controls on the MasterPage in the Page_Load event handler (shown below).
protected void Page_Load(object sender, EventArgs e)
{
breadCrumb.BreadCrumbs = BreadCrumbs;
header.MenuItems = MenuItems;
footer.Footers = Footers;
head.Controls.Add(CreateCssLink("~/Stylesheets/main.css", "screen"));
head.Controls.Add(CreateJavaScriptLink("~/Scripts/site.js"));
if (Context.Session != null && Session["layout"] == null) Session["layout"] = "single";
if (!ArePreferencesVisible) preferences.Visible = false;
}
I want to be clear here... there are no errors in this code. There are correctly named elements in the MasterPage that correspond to those in this code. It has always worked as expected up until today and I have not changed any code since it was last working. I now get a NullReferenceException on the first line because the breadCrumb element is null. In fact, all the elements from the page that are referenced here are null.
Normally the page elements have been initialised by the time the Page_Load event is raised. What can have caused this to stop happening?
I have double checked that the MasterPage and its code behind file are still connected and they are. I also tried moving this code to the Page_LoadComplete event handler, but the controls had still not been initialised, even at that stage. I shouldn't really have to change the code because it worked just fine before.
I also commented out this code and the website ran, albeit without any styles. Interestingly, when I returned the original code to the event handler and refreshed the page, it actually worked again just as it used to. I loaded a number of different pages successfully and I thought it had fixed itself, so I restarted the application and then got the same error again. No amount of cleaning, building, changing solution configuration or restarting the application and Visual Studio make any difference.
I'm not sure if the app_offline.htm is a red herring, but I've never seen that before either so it might be connected somehow. From what I read, it seems that just removing it causes the server to restart the application domain automatically, so I can't see the connection.
I really hope someone has come across this bizarre situation before because I'm all out of ideas and I can't run my website until this is fixed.
Ok, so I finally tracked down the problem. I had an earlier backup of the website from a few days ago, so I loaded that up and it worked, albeit missing the last few days' work. I copied the latest project code into the Visual Studio > Projects folder leaving the old code in the Visual Studio > Website folder. I loaded the solution and it ran fine again.
I basically compared the Website files, updating each one in turn and periodically running the application. Eventually, the application stopped working. The last file that I had updated was a MasterPage file that extended the MasterPage that had the problem.
What I had done was comment out an empty Page_Load event handler in the MasterPage. I don't understand why that would cause this problem, so any comments explaining that would be helpful and appreciated.
This MasterPage is only used on the home page and a few others, so that explains why I didn't come across the problem the night that I changed it. (I hadn't viewed any pages that used that MasterPage after making the change). I wish I had because it would have been much easier to track down then, but such is life.
So I replaced all of my latest code, added the empty Page_Load event handler in the MasterPage again and finally, everything is working again.

Most elements of an ASP.NET page are not rendered after random idle time

We have been trying to figure this one out for a while now, without any luck.
The symptoms are as follows:
After some idle time of a specific ASP.NET 2.0 application (can be from several hours to days), one of the pages in my application stops working.
When viewing the source of the page I see many elements missing, elements that are usually there, such as: reference to WebResource.axd, the __doPostBack() function, all of the UserControls and more.
A reference to ScriptResource.axd, and the __VIEWSTATE are there.
After recycling the app pool, the application starts working correctly again and everything renders well.
This only happens on a specific server, when deploying the same application on a different server, this error does not occur.
The page that the error occurs on has only one UserControl which is not rendered when the error occurs. Nothing special happens when this page is loaded.
We tried doing periodic client refreshes, but that did not help either.
Thanks in advance.
It was a caching issue. There was a part in the code that hid specific controls when the cache was invalid. That explains the missing code parts.
I am still not sure why the cache was invalid on that specific server.

"Validation of viewstate MAC failed. If this application is hosted by a Web Far..."

i am facing the dreaded:
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Error.
Ok so i looking it up and found that it can be caused by two things, viewState which can not be verified by the page, and/or events that can not be validated.
I put
<pages enableEventValidation="false" enableViewStateMac="false" viewStateEncryptionMode="Never">
In my web.config to stop the problem, but that hardly seems like a fix to me.
The thing is, i never even used viewState in my application. I know that asp.net uses viewstate by default to store some things, but i doubt the default values stored here will cause any errors.
I noticed that the problem seems to happen when i postBack and the page has not finished loading yet.
Thanks
Edit: Please, can someone test my website www.vittoriosaStarsNursery.com and see if you get the error i got above? I dont get it locally but people keep telling me they are getting it.
Isnt this just a case of putting a one liner in your web.config
<machineKey decryptionKey="A4B12CCDD50E95F8GB9GFH6JKAT4Y0U0I2OF2DF2AAFE5AB46189C,IsolateApps" validation="AES" validationKey="480CDF2AS9S9AS5CFDGF0GHFH9JJH4KHKAKLJ2L9F3SAS82A6C16911A29EF48903783F94529C21570AACB72766FB38CD4CE7B85B0ACE3149DC5FC1CCF1AA1CECE3579659996593B06,IsolateApps"/>
One thing I have come across that causes this issue has to do with the recycling intervals of the app-pools on the webserver.
I found this by looking at the event information in Eventviewer/Application logs and the "Task Category" called "Web Event". Then for the time period that this event took place I looked to see if there were any recycled events that took place just before that (Eventviewer/System logs and the "Source" called "WAS".
By default an app-pool will recycle every 1740 minutes (29 hours). If this recycle happened while a user is busy on the site and send post back to the server, the server no longer recognizes the session/viewstate and rejects what is being posted back.
To overcome this from our perspective is to set the recycle event to happen at a specific time of the day when we don't expect activity on the site. In our case 3am in the morning.
Hope that helps someone out there.
You're not going to like my answer. This error is basically unavoidable in webforms. My solution was to leave webforms for MVC3 and razor.
I noticed that the problem seems to happen when i postBack and the
page has not finished loading yet.
this is one of the easiest ways to cause this error. In ASP.NET 3.5 (or 4.0) there's a setting that you can make sure viewstate gets loaded very early in the page to try to help diminish it. It still doesn't solve it.
Chunking the viewstate doesn't solve it.
There is just something inherently wrong to the way webforms works that this error will plague your application at random times forever.
At my site, this meta tag were causing the error:
<base href="http://www.SITEURL.COM" />
I have a dropdown, I update on another dropdowns changed selection. So when the postback happened (dropdown #2 changed index), I got the exception.
I've tried everything else from applying machinekey to web.config and setting theese attributes at the page
EnableViewState="false" EnableViewStateMac="false"
I am using VS 2010 against a Windows Web Server 2008 and what I eventually found was that I had two keys set for the same service in the appSettings section of webconfig. I went to IIS and checked the Application Settings on the virtual directory and got an error, fixed it in the WebConfig and the problem resolved. I did create a machine key but that did not fix the problem. Nor did the
pages (...) validateRequest="false" enableEventValidation="false"
enableViewStateMac="false" viewStateEncryptionMode ="Never"/
Settings. FWIW ...
I used this Microsoft article to create my own machineKey validationkey and decryptionKey. As others have stated, this can be placed within the system.web section of web.config, though there are security concerns if other people get hold of the key.
Well, yes i suppose disabling encrypted viewstate solves the problem but i have never tested it nor do I advise it. Viewstate stores the state of controls and is also very convenient for storing persistent variables.
Take for example you work for a garage and have a list of jobs. You go to a page that lists the jobs. Now you click a job which goes to another page appending the jobid (eg. job.aspx?id=1). On that page, there is a checkbox which marks the job as complete. Once you tick that checkbox, it posts data back to same page and writes to the database that the job is complete. But how does the server know which job to mark as complete because you have only posted back true or false from the checkbox. However, if the first time you load the job details page you record the job id in Viewstate, then when you post pack the checkbox, you can read in the jobid from the viewstate.
Why is it not good to use unencrypted viewstate?
Imagine what the server has to do to mark the job as complete. It probably has to run an sql command to update the database. Something like UPDATE jobs SET completed=GETDATE() WHERE id=1.
If your viewstate wasnt encrypted and i could add my own job id, I would put something like '; DELETE FROM jobs;' which would then cancel out the initial UPDATE command and delete ALL your jobs... not very good for the garage :)

Runtime HttpException affecting only one page/usercontrol

We're having an issue with a .NET 3.5 WebForms site where occasionally our error logs start filling up with the following error message:
"Multiple controls with the same ID 'ctl09' were found. FindControl requires that controls have unique IDs."
I know very little about the exception as I have never seen it while debugging locally and have never caught it in the error logs soon enough to run a remote debugging session. I do know that an application pool recycle fixes the issue.
This only affects a single [high traffic] page in the site. The strange thing is that the site uses the pre-4.0 ID generation logic. So, when the page is working, there isn't an html element in the entire view source that isn't some autogenerated control ID prefix followed by a the 'actual' IDs (i.e. ctl09_someID_someOtherID).
So, 2 primary questions, though any ideas are welcome:
What would case a control to randomly stop being built correctly?
Other than the Global.asax, how can I trap this error and force the control to ... recompile? App pool to recycle?
I'm pretty much stumped.
Nothing as far as I'm aware, only an outside entity interferring with the page lifecycle or AJAX postback could potentially cause this, if each control is being generated, in turn, then you will not 'randomly' experience duplicate ids.
I don't think this is a viable option, app pool recycle? No way, there's got to be a valid reason for this.
Perhaps some more info/code would be useful? Is it a particular page? Are you using ViewState? There's lots of reasons for 'dodgy' control ids.

Why doesn't my page have session state when called as the default document of a directory?

If I access my page like this...
/folder/default.aspx
...everything is fine. If I access it like this...
/folder/
...the page has no session state. Any ideas why?
This changed from IIS6 to IIS7, incidentally. In IIS6, it was fine. The "Default Document" feature in IIS7 is enabled, set to "default.aspx".
This is quite a mystery. One way you could try to discover the source of the problem would be to set breakpoints at several events in Global.asax and in the .aspx page. You'll have to write the code to create the event handler. Then, put some code in there to examine, for example, whether Session is null. Finally, step through and see if you can identify where the two URLs differ in behavior.
Events that I would start with include Application_Start, Session_Start, and especially Application_BeginRequest and Application_AcquireRequestState. There are other events interleaved in there that you might want to add once you've narrowed it down.

Resources