I get the following error in the production environment
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 configuration\system.web\httpModules section in the application configuration.
The following things I have tried as of now
Checked machine.config and web.config, both have enableSessionState="true"
Added enableSessionState="true" to pages in web.config
State module is also added in <httpmodules> section
Even tried setting enableSessionState="true" in page directive
Note: When I try to debug the code in Dev environment, everything works fine as it should.
Can anyone help me out getting over this issue, I just can't figure out a way out of it.
What does your session state config look like? You probably want to be set up to use inproc session handling.
http://msdn.microsoft.com/en-us/library/ms178586.aspx
I know this is a late response but I just want to add how I fixed the same problem.
First I want to emphasize that I'm using web forms, not MVC - this may not work for MVC.
I created a web form that contained the class ContactUser and I created my own constructor so it looked like:
public ContactUser(String to, bool isUser)
{
...
}
And in this I tried to access a session variable:
String user = Session["username"]
It turns out that you CANNOT use the session state in the constructor of a class, but you can use it in other functions that you write and in the protected void Page_Load(object sender, EventArgs e) procedure. So once I moved session state out of the constructor into the page load procedure everything worked :)!
Hope this helps anyone that runs into the same problem :D!
Related
Due to some security concerns i need to enable View State Encryption. I have viewstate & viewstateMAC turned off but i need to encrypt the "control state" string that is included in the __VIEWSTATE form parameter.
Currently my web.config looks like:
<pages enableViewState="false" enableViewStateMac="false">
When i set the following, in cassini, my viewstate is encrypted:
<pages enableViewState="false" enableViewStateMac="false" viewStateEncryptionMode="Always">
When i make the same change on my IIS 6 server, nothing happens.
I see the app domain recycle(Event: Application '/LM/W3SVC/...' located in 'C:...' initialized for domain '...'). when i touch web.config but i do not get encrypted viewstate as with cassini. I have tried Site Stop/Start, IIS Reset Stop/Start, Clear ASP.NET Temporary file cache. Anyone have any suggestions on what needs to be done to configure this?
I ran into a similar problem with this and it came down to the fact that if you pre-compile your site the web.config node for pages is ignored. You have to set those settings at compile to get it working. I know this is year late, but I figure if someone else comes here looking for solution to the problem this might be useful information.
A little blurb about this: http://blogs.msdn.com/b/asiatech/archive/2011/07/19/pages-settings-don-t-work-for-pre-compiled-asp-net-applications.aspx
(Link dead - blog pointed to this documentation: ASP.NET Web Site Project Precompilation Overview )
My customer had a viewstate MAC
validation problem. As a workaround, he wanted to disable the
viewstate MAC validation before find out the final solution. However,
he was still seeing the problems after added follow settings in the
configuration files.
Customer’s application is a pre-compiled ASP.Net application with
updatable option disabled. Looking at the code generated by compiler
with above settings, we found these settings are hard coded. So, this
means simply add the above setting into web.config doesn’t affect a
pre-compiled application. To make this taking affect, the application
has to be re-compiled.
[DebuggerNonUserCode]
private void __BuildControlTree(default_aspx __ctrl)
{
__ctrl.EnableViewStateMac = false;
__ctrl.EnableEventValidation = false;
__ctrl.ViewStateEncryptionMode = ViewStateEncryptionMode.Never;
This is a by-design behavior.
I have made something like the following code:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["loginid"].ToString();
}
protected void delete_click(object sender, EventArgs e)
{
delete("mail1",Session["loginid"]);
}
private int delete(string mailid, string user)
{
System.IO.Directory.Delete(Server.MapPath(#"~\files\" + user + #"\" + mailid), true);
}
When i press the delete button, everything works fine and the folder gets deleted.
but after that when page postbacks again then a
NullRefrenceException is raised at
Label1.Text = Session["loginid"].ToString();
why is it happening...??
When I am not using this Directory.Delete() method everything is working fine and session variables are not set to null.
When I traced my application I found that After Directory.Delete() method Session variables were intact and I was able to use those session variables in the processing after Directory.Delete().
But as soon as the page postbacks all session variables are set to null.
And this problem doesn't appear when i m not using this delete() method.
The folder I m deleting is in my project's folder.
I m running this website using Visual Studio.
Please help.
Just another guess here but maybe it's because your modifying something in your applications directory (a hunch since your using Server.MapPath with the ~). IIS maybe thinks the app has changed and recycles the application and as a result wipes out all sessions.
This is similar to if you modify your web.config file while someone is using the app and it drops all sessions and recycles the app. Are you deleting a directory that may contain information that IIS is using for the application?
You said it only happens when you include that line of code and a session will really only get wiped out consistently (unless you are doing it yourself manually) when the application is recycled by IIS or times out. It is obviously not timing out so the recycle must be what is happening.
Is your 'files' folder in your web application folder? Maybe application restarting itself when you deleting the files. Try to use sessionStateServer. Its keep sessions alive.
Web.config:
<configuration>
<system.web>
<sessionState mode="StateServer"></sessionState>
</system.web>
</configuration>
Deleting a folder in your virtual directory may cause your application to re-start, thus loosing all session data. To prevent this, either delete individual files (not folders) or use the StateServer to maintain your sessions.
Since the page loads correctly before you press the delete button, the problem is presumably with the Session["loginid"].ToString() reference. Do you have any other code that references Session["loginid"]? The code you have shown here won't do anything that removes loginid from the Session.
However, if this application is running on a server cluster and you're using the default session mode of in-process, you may be losing access to your session between HTTP requests because they're handled by different servers. See here for more information.
If I remove the directory.delete()
function from the code then the whole
application is running so fine without
any exception
Ok, seems that we found your problem. Your project does not have the necessary privileges to delete the direcotry (even if the directory is deleted.nevertheless: there are privilege problems)
I guess that you're application is throwing an exception while performing this file operation and a new session begins. I have a similiar situation on one of my projects, but I still haven't figured out how to solve it.
I'm pretty sure you will concur with description if you create the Global.asax and set breakpoints on Application_OnError and Session_OnStart (or however these methods are spelled correctly). You will see that the an error is raised and afterwards a new Session is started.
First, a couple of sanity checks:
Does session work as expected on other pages?
Is your Delete method deleting files in a special ASP.NET folder, like App_Data or App_Code, which may be causing the application to restart?
Here's what I would try to debug this issue, after checking the above:
Set a breakpoint on the delete method and have the session variable in a watch window. See what the value of the session variable is before the call to Directory.Delete is and what it is afterward. Is it at that point when you're losing session, or is not until the next page visit?
Use a tool like Fiddler to examine the cookies exchanged between the browser and web server on postbacks. Check that when the browser first visits a new session cookie is created and stored on the browser. Then, when deleting the folder, see if the web server is sending a new session cookie on the response of that postback. This would indicate that a new session has been created.
Thanks
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.
I have a simple ASP.NET 3.5 SP1 Web Forms app... I've added the System.Web.Routing DLL, and I've made a simple route that returns a standard ASP.NET Page as the "IHttpHandler".
All is good... except that HttpContext.Current.User is null ???
So, I did a little more digging (I put breakpoints in all the events in the Global.asax file). Normally, these breakpoints get hit (when I navigate to a standard ".aspx" page):
Application_BeginRequest
Application_AuthenticateRequest
Application_EndRequest
But, when using ASP.NET Routing... none of those events are firing. Am I missing something?
Assuming you're using IIS6, the alternative is to define a "wild card" extension handler. Adding this simple "catch all" mapping to IIS6 will enable it to process your extensionless requests. By default, the .NET installer maps ".aspx" to the aspnet_isapi.dll- that's why the .aspx extension works. To map requests with no extension to the APS.NET engine, you must tell IIS to look at every request.
Here's a quick article that explains the process:
http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx
Hope that helps and reduces the "lame" factor of your URLs. :)
-Todd
Found the freakish and bizzare (and stupid) answer :)
If you don't add ".aspx" to the end of your route, nothing fires in the Global.asax, meaning you don't get any BeginRequest, AuthenticateRequest, EndRequest, etc... Also, you don't get SessionState or anything.
So, the "fix" was for me to just change my route from this:
RouteTable.Routes.Add("Blah", new Route("Blah/{reportName}", new MyHandler());
to this:
RouteTable.Routes.Add("Blah", new Route("Blah/{reportName}.aspx", new MyHandler());
How completely lame :) ... but it's a fix none-the-less!
When you say
"If you don't add ".aspx" to the end of your route, nothing fires in the Global.asax, meaning you don't get any BeginRequest, AuthenticateRequest, EndRequest, etc... Also, you don't get SessionState or anything."
Will IIS log such requests in the log files or they are just anonymous? what about Application variables and ViewState?
sorry i haven't tested it yet, but just asking if you might already know?
i have checked application variable and Viewstate, these two are obviously working.. not sure about server logs :S
What is a good way to edit a Web.config file programmatically?
I looked into System.Xml but couldn't find any obvious answers.
This fellow shows sample code if you still want to do it after all the caveats:
protected void EditConfigButton(object sender, EventArgs e)
{
Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
//Edit
if (objAppsettings != null)
{
objAppsettings.Settings["test"].Value = "newvalueFromCode";
objConfig.Save();
}
}
One valid reason for editing a web.config is to encrypt it, which is what that article is about.
You can use the WebConfigurationManager to read specific configuration sections. This will return a ConfigurationSection object. You can use this to read/modify the ConfigurationElements in the section. Once you have updated them, you can Save the ConfigurationSection and it will update the file with your changes.
I use this to automatically encrypt the appSettings and connectionStrings on Application_Start if they aren't already encrypted. I haven't actually changed any settings this way, but it seems like you ought to be able to do so.
Saving the updated configuration file may cause the app to recycle depending on how it is built.
Depending on what you are doing, the method is really a bit different in each situation. However the most robust method is to load it as an XmlDocument and modify it as needed via that method, but you MUST be careful to only modify it in the needed manner.
In theory; you could just generate a web config file programmatically and with some templating to make it easy.
However, if you're trying to edit your web.config from within the site; it's highly recommended you don't. At the very least; you'd trigger an app reset every time you updated it; which would be especially bad if you're using in-process sessions.
As Anders asked, what is it you're trying to do?
Yes I agree with Josh. I have tried this before and I've had two negative effects:
Slow loading if the current page after postback because ASP.NET is loading the web.config and all related resources
If you change the web.config early enough in the load cycle (e.g. global.asax events) the site may never load or fail in unpredictable ways
Agree with others, editing the webconfig is achievable, but has knock on effects are just to dangerous / risk involved
If its a value that is application specific, then it should be in an application specific config file
Lot of time you want to modify application specific settings after deployment like say when something is wrong e.g. switching the database connection in case current DB goes down. Moreover sometimes you want to create your own XML based configuration file which you want o modify programatically.
Try XML Webpad - http://xmlwebpad.codeplex.com/
Its a framework to view an edit XML files. Once you integrate it with your web app, editing web.config ill be as simple as viewing the web.config page, making the required changes and hitting the save button (all from within your application).