I’ve created a webpage which is inherited from another class something like :
class webpage : startup {
.
.
.
}
class startup : System.Web.UI.Page {
}
and inside startup class I’m trying to use
Session["blah"] = "some other blah";
but whenever I run this code I’ll get the following error :
Session state can only be used when
enableSessionState is set to true,
either in a configuration file or in
the Page directive. Please also make
sure that
System.Web.SessionStateModule or a
custom session state module is
included in the
\\
section in the application
configuration.
I’ll get error even after changing web.config to accept Session but again the same result
————————edit——————–
I know I can use Httpcontext.current.session but this approad also give me error saying :
“you can’t use null instance or something like that”
what should I do?
I’ve created a
BasePageclass as follows:And a default page that inherits from
BasePage:I have no problems accessing session at all. Not sure what the issue is, but having inherited from another class beside Page is most likely a red herring.
This one is going to be difficult to diagnose without including a lot of details. The best advice I can give is to create a blank ASP.Net project, and start porting things over one by one so you can eliminate possibilities systematically.
UPDATE
Mr. Powers was kind enough to send me a test solution that recreated the problem.
The issue lies within the idiosyncrasies of the ASP.Net Page Life Cycle. The offending code looked something like this:
Unfortunately, trying to access Session in the constructor is a non-starter because the Request and Response objects aren’t set until after the constructor is called. The trick is to move your code into a stage where those things have been initialized, but before other dependent code might need to take advantage of it.
The PreInit event will do the trick. If you get rid of the constructor, and override the OnPreInit event, then everything should be fine. Like this:
Understanding the Page lifecycle is a critical component to doing anything in ASP.Net. One should read the MSDN documentation thoroughly before proceeding any further with Web Forms as it will save many a headache down the road.