Solved

Session state not working

Posted on 2015-02-11
14
625 Views
Last Modified: 2015-02-23
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
Comment
Question by:Tom Knowlton
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 4
  • 2
14 Comments
 
LVL 13

Expert Comment

by:Jitendra Patil
ID: 40605045
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
 
LVL 36

Expert Comment

by:Miguel Oz
ID: 40605214
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
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 40606975
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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
LVL 36

Expert Comment

by:Miguel Oz
ID: 40607428
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
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 40610297
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
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 40610304
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
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 40610305
In the code-behind, it is line 26 that the exception fires on:

    if (Session["loggedin"] != null)
0
 
LVL 36

Accepted Solution

by:
Miguel Oz earned 450 total points
ID: 40610411
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
 
LVL 13

Assisted Solution

by:Jitendra Patil
Jitendra Patil earned 50 total points
ID: 40610536
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
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 40623297
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
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 40623318

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
 
LVL 36

Expert Comment

by:Miguel Oz
ID: 40623543
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
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 40626173
Thank you.


It seems much more stable now.  No sign of the http context error any longer.
0
 
LVL 5

Author Closing Comment

by:Tom Knowlton
ID: 40626180
Thanks everyone.

This was the key:

>>> .. replace Session with HttpContext.Current.Session...
0

Featured Post

Stack Overflow Podcast - Frustrating Miracles

In this podcast, Stack Overflow interviewed Linux Academy CEO/Founder, Anthony James, and got his developer story!

"Follow your passion, be prepared to work hard and sacrifice, and, above all, don't let anyone limit your dreams."  - Donovan Bailey

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

635 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question