Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 789
  • Last Modified:

Session state not working

I keep getting this error:

An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code

Additional information: 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.
 
I've tried following the above suggestions but it seems to make no difference.
0
Tom Knowlton
Asked:
Tom Knowlton
  • 8
  • 4
  • 2
2 Solutions
 
Jitendra PatilSr.Software EngineerCommented:
can you post your code here so that we can provide you the correct solution.

as the error says "Session state can only be used when enableSessionState is set to true," please check the same whether session state is enable on not your page, it can be checked on the first line of your .aspx page in the page directive tag.
0
 
Miguel OzSoftware EngineerCommented:
Al the last part of the error message states the problem could be in the web.config file(s) of your site.
Typical sessionState entry looks like:
<sessionState mode="InProc" timeout="60" />
If more help needed please post your web.config  containing sessionState info and Global asax code. You should include page code as well. (as requested by @Patil)
0
 
Tom KnowltonWeb developerAuthor Commented:
Okay.  It may be a day or two before I can come back and post the requested code, but I will do so.  It's a home project and I am at work at the moment.

I don't remember "Session" being so difficult to use.

Tell me -- does it make a difference if I am running this on my local machine vs an actual web server?  For example...using the Visual Studio IDE vs IIS on my local machine?
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Miguel OzSoftware EngineerCommented:
Yes, it depends on whether you have hard coded local paths in your site. e.g. connection strings? Path locations?
VS sorts out a lot of permissions for you as well...
0
 
Tom KnowltonWeb developerAuthor Commented:
my current web.config:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
          <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
          <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
          <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-ukf-20141618;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-ukf-20141618.mdf" providerName="System.Data.SqlClient" />
    <add name="ukfdatabaseConnectionString" connectionString="Data Source=184.999.21.15;Initial Catalog=mydatabase;Persist Security Info=True;User ID=webmaster;Password=mustang3_" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>       
    <httpModules> 
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule" />      
    </httpModules>
    <compilation debug="true">
      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
        <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
      </assemblies>
    </compilation>
    <httpRuntime />
    <pages>     
      <controls>        
        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </controls>
    </pages>
    <authentication mode="None"></authentication>
    <httpHandlers>
      <remove verb="*" path="*.asmx" />
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </httpHandlers>   
  </system.web>  
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
        <providerOption name="CompilerVersion" value="v3.5" />
        <providerOption name="WarnAsError" value="false" />
      </compiler>
    </compilers>
  </system.codedom>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ScriptModule" />
      <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </modules>
    <handlers>
      <remove name="WebServiceHandlerFactory-Integrated" />
      <remove name="ScriptHandlerFactory" />
      <remove name="ScriptHandlerFactoryAppServices" />
      <remove name="ScriptResource" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </handlers>
  </system.webServer>
</configuration>

Open in new window








my current global.asax.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using ukf;

namespace ukf
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {

        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

        }
    }
}

Open in new window



HTML for control that generates the error:

<%@Control Language="C#" AutoEventWireup="true" CodeBehind="LoginManager.ascx.cs" Inherits="ukf.LoginManager" %>

<asp:HyperLink ID="HyperLinkLogin" NavigateUrl="~/Login.aspx" runat="server">login</asp:HyperLink>
<asp:HyperLink ID="HyperLinkRegister" NavigateUrl="~/CreateUserAccount.aspx" runat="server">register</asp:HyperLink>
<asp:Label ID="LabelLoginStatus" runat="server" Text="Not Logged In"></asp:Label>

Open in new window



current code-behind for user control that generates the error:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ukf
{
    public partial class LoginManager : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Page_Init(object sender, EventArgs e)
        {
            Common.loggedin += Common_loggedin;
        }

        void Common_loggedin()
        {
            try
            {
                if (Session["loggedin"] != null)
                {
                    if ((bool)Session["loggedin"])
                    {
                        HyperLinkLogin.Visible = false;
                        HyperLinkRegister.Visible = false;
                        LabelLoginStatus.Text = "Welcome, " + Session["username"].ToString();
                    }
                    else
                    {
                        LabelLoginStatus.Text = "Not Logged In";
                        HyperLinkLogin.Visible = true;
                        HyperLinkRegister.Visible = true;
                    }
                }
            }
            catch(System.Web.HttpException he)
            {
                System.Diagnostics.Debug.WriteLine(he.GetHtmlErrorMessage());
                System.Diagnostics.Debug.WriteLine(he.GetHttpCode());
            }
        }
    }
}

Open in new window

0
 
Tom KnowltonWeb developerAuthor Commented:
Yes, it depends on whether you have hard coded local paths in your site. e.g. connection strings? Path locations?
VS sorts out a lot of permissions for you as well...

I don't know of any hard coded paths.

I searched my projects for anything that looks like:

C:\

or

C:\ukf

and nothing was found.  I have read about URL re-writing being a potential problem with session state, but I don't think I am doing any of that.


The web.config resides at this location on my local drive:

C:\ukf\ukf
0
 
Tom KnowltonWeb developerAuthor Commented:
In the code-behind, it is line 26 that the exception fires on:

    if (Session["loggedin"] != null)
0
 
Miguel OzSoftware EngineerCommented:
Q1. What version of OS, IIS, VS and .NET are you using?
Q2. Is this a new asp.net MVC/webform development or upgrade?
Note: In a VS2013 app, web.config typically contains this element <compilation debug="true" targetFramework="4.5.1" />
Q3. When you call line 26, is the user already authenticated at this stage of your page lifecyle?

Notice that  your web.config does not contain a sessionstate  element, thus you need to check:
1. Whether your IIS Session state settings are enabled in your machine
2. Your page directive contains <%@ Page EnableSessionState="true" %>.
3. If you replace Session with HttpContext.Current.Session. Does it work?
0
 
Jitendra PatilSr.Software EngineerCommented:
as per your code I think your are using a different class to maintain session variables.

for more information please check the below link.
What is the best way to determine a session variable is null or empty in C#?

hope this helps.
0
 
Tom KnowltonWeb developerAuthor Commented:
as per your code I think your are using a different class to maintain session variables.

Open in new window


It's true, I am:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ukf
{   
    public partial class Login : System.Web.UI.Page
    {
       
        
        protected void Page_Load(object sender, EventArgs e)
        {        
        }

        protected void ButtonLogin_Click(object sender, EventArgs e)
        {
            if (Common.UserNameExists(WizardTextBoxUserName.GetTextBoxValue, WizardTextBoxPassword.GetTextBoxValue))
            {
                Session["username"] = WizardTextBoxUserName.GetTextBoxValue;
                Session["loggedin"] = true;
                Common.FireLogIn();
            }
            else
            {
                Session["username"] = null;
                Session["loggedin"] = null;
                Common.FireLogOut();
            }
        }
    }
}

Open in new window





Common.FireLogOut();

Is how I fire the event that lets the LoginManager control update itself.
0
 
Tom KnowltonWeb developerAuthor Commented:

Q1. What version of OS, IIS, VS and .NET are you using?
Q2. Is this a new asp.net MVC/webform development or upgrade?
Note: In a VS2013 app, web.config typically contains this element <compilation debug="true" targetFramework="4.5.1" />
Q3. When you call line 26, is the user already authenticated at this stage of your page lifecyle?

Notice that  your web.config does not contain a sessionstate  element, thus you need to check:
1. Whether your IIS Session state settings are enabled in your machine
2. Your page directive contains <%@ Page EnableSessionState="true" %>.
3. If you replace Session with HttpContext.Current.Session. Does it work?


Q1. What version of OS, IIS, VS and .NET are you using?
OS:  Windows 8
IIS:  Whatever comes with Windows 8 .. 8.5.x ?
VS:  Visual Studio Express 2013 for the Web
.NET:  Target framework is 3.5


Q2. Is this a new asp.net MVC/webform development or upgrade?
It is a webform development project I made from scratch.


Note: In a VS2013 app, web.config typically contains this element <compilation debug="true" targetFramework="4.5.1" />
Q3. When you call line 26, is the user already authenticated at this stage of your page lifecyle?

My intent is for the user to already be authenticated at this point -- I am just intending to update the UI to show this fact.


Notice that  your web.config does not contain a sessionstate  element, thus you need to check:
1. Whether your IIS Session state settings are enabled in your machine

In IIS, session state is set to "In Proc"

2. Your page directive contains <%@ Page EnableSessionState="true" %>.

Is that okay?

3. If you replace Session with HttpContext.Current.Session. Does it work?


So far .....  YES !!!  The error has not shown-up since I made that change.


But isn't Session referencing the same Session as HttpContext.Current.Session ?
0
 
Miguel OzSoftware EngineerCommented:
Regarding your last Session comment, yes In principle both are the same, but it depends how other areas of your code executes.
Possible issues:
1)  .NET 3.5 web forms may have a bug handling session context from user control to page. Notice that .NET 3.5  is not supported in Windows 8 out of the box and you need to enable it. Unless you are supporting a legacy site, any new development should use the latest 4.5 version or at least  .NET 4.0.
2)  Use of Response.Redirect in your code  as shown here.
0
 
Tom KnowltonWeb developerAuthor Commented:
Thank you.


It seems much more stable now.  No sign of the http context error any longer.
0
 
Tom KnowltonWeb developerAuthor Commented:
Thanks everyone.

This was the key:

>>> .. replace Session with HttpContext.Current.Session...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 8
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now