Session variables are lost with every request even though session persists

Hi,

I am new to .NET and this is my first application with session state management. I am using .NETs login controls and database for login/password security management. I have a folder called "secure" which requires the user to login. The login page itself is out site this folder. Once a correct a correct login/password are provided I store the UserID in session and redirect to next page inside "secure" folder.The problem is that session["userID"] is null on the next page even though Context.Session is not. I tried to add UserID in session again on a page inside "secure" folder but that too gets lost once I move to another page, although it is available on the same page. I think I am screwing up some setting in my web.config file. Below are the code snippets:

<!-- after successfull login/password, adding userID to session -->

protected

void InfograteLogin_LoggedIn(object sender, EventArgs e)

{

FormsAuthentication.RedirectFromLoginPage(InfograteLogin.UserName, false);

MembershipUser CurrentLogin;

CurrentLogin =

Membership.GetUser(InfograteLogin.UserName);

string UserID = CurrentLogin.ProviderUserKey.ToString();

Session.Add("UserID", UserID);

 

string RedirectPageTxt;

if (Request.QueryString["ReturnUrl"] != null)

RedirectPageTxt = Request.QueryString[

"ReturnUrl"].ToString();

else

RedirectPageTxt =

"secure/Default.aspx?UserId=" + Session["UserID"].ToString();

Response.Redirect(RedirectPageTxt);

 

}

<!-- web.config file in root folder -->

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
 <appSettings/>
 <connectionStrings>
  <clear/>
  <!-- Connection string for connecting to DB for this app -->
  <add name="InfograteSQLServer" providerName="System.Data.SQlClient" connectionString="Data Source=(local); Integrated Security=SSPI; Initial Catalog=MyDB;User ID=sa;Password="/>
 </connectionStrings>
 <system.web>
  <roleManager enabled="false" />
    <!-- Themes and Session -->
  <pages theme="MSN_Purple" enableSessionState="true" enableViewState="true" enableViewStateMac="true" validateRequest="true" autoEventWireup="true" />
  <!-- Membership information-->
  <membership defaultProvider="MyMembershipProvider">
    <providers>
      <clear/>
      <add name="MyMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="InfograteSQLServer" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="Infograte" requiresUniqueEmail="true" passwordFormat="Clear"  maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
    </providers>
  </membership>
  <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
  <authentication mode="Forms">
    <forms name="My_SessionID" loginUrl="Default.aspx" protection="All" timeout="40" path="/" />
  </authentication>
  <!-- Session State Mgmt -->
  <sessionState cookieless="AutoDetect" cookieName="My_SessionID" regenerateExpiredSessionId="false" timeout="40" mode="InProc" />
     <compilation debug="true">
      <assemblies>
        <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="ADODB, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
       
      </assemblies>
    </compilation>

 

        </system.web>
</configuration>

<!-- web.config file in secure folder -->

<?

xml version="1.0"?>

<configuration
>

<

appSettings/>

<

connectionStrings/>

<

system.web>

 

<!--

Authorization: Dont allow anonymous users, allow only logged in ones -->

<

authorization>

<!--

<deny users="?"/>-->

<

allow users="*"/>

</

authorization>

 

</

system.web>

<

location path ="data.aspx">

<

system.web>

<

httpRuntime maxRequestLength="1048576" executionTimeout="54000"/>

</

system.web>

</

location>

</

configuration>


 
0
datuca
4/11/2007 2:07:10 AM
asp.net.state-management 8807 articles. 0 followers. Follow

2 Replies
1488 Views

Similar Articles

[PageSpeed] 17
Get it on Google Play
Get it on Apple App Store

You are redirecting from your login page before you even add the users id to the Session..

 FormsAuthentication.RedirectFromLoginPage(InfograteLogin.UserName, false);

This should be the last thing to execute in your method.

 From MSDN

The RedirectFromLoginPage method redirects to the URL specified in the query string using the ReturnURL variable name. For example, in the URL http://www.contoso.com/login.aspx?ReturnUrl=caller.aspx, the RedirectFromLoginPage method redirects tothe return URL caller.aspx. If the ReturnURL variable does not exist, the RedirectFromLoginPage method redirects to the URL in the DefaultUrl property.

Thus this code

string RedirectPageTxt;

 

if (Request.QueryString["ReturnUrl"] != null)

RedirectPageTxt = Request.QueryString[

"ReturnUrl"].ToString();

 

else

RedirectPageTxt =

"secure/Default.aspx?UserId=" + Session["UserID"].ToString();

Response.Redirect(RedirectPageTxt);

is not required. Delete it, thats what your RedirectFromLoginPage is supposed to do for you.

Atleast, I hope I have read this correctly :) Good luck with it and hope this works for you.

0
parheric
4/11/2007 7:16:32 AM

Hey parheric,

Thanks for your reply. Tried it but it still does not work. The Session["UserID"] is not available in page other than where it is set.

Context.Session is not null but Session["UserID"] is null

0
datuca
4/12/2007 4:50:36 AM
Reply:

Similar Artilces:

Session state lost every other session after conversion from 2003 to 2005
Hi, I have a weird problem here I can't really place. Maintaining session state was never a problem with VS2003 but after the conversion to VS2005 I have session state problems.I put a value in the session state in the !IsPostBack in Page_Load. After that if statement I take out that variable again just to test if it is in the session state. This goes ok for the first time I work with th e application. If I then close the browser and go to it again this fails. After the postback the webapplication doesn't enter the !IsPostBack if statement but the variable is also not in the Ses...

Unable to make the session state request to the session state server.
 Hello,           I’m receiving this error when I put my website on production."Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection.  If the server is on the local machine, and if the before men...

Unable to make the session state request to the session state server
Hi all, I'm working on the website http://universityauction.net and I was using session variables using InProc session mode to manage session state. This worked fine until I put the website in a load balanced environment, as inproc sessions get lost when jumping from server to server. I decided to move to a state server mode, so I changed my web.config to: <sessionState             mode="StateServer"             stateConnectionString="tcpip=123.456.7.8:42424"      ...

Unable to make the session state request to the session state server etc.
We are getting an error message "Unable to make the session state request to the session state server..." sporadically in one of our applications.  We have several applications running on a 4-server web farm, and these applications have been in production for a year, so it is not a problem that the server is not reachable, not started, not addressed correctly, etc etc etc. One of the applications *does* put a lot of large datasets into session state.  Is there a limit on the allowable size of a session/cached object?  Also, the application opens several windows at once, ...

Error: Unable to make the session state request to the session state server
I have session configured in web.config this way:<sessionState mode="StateServer" cookieless="true", timeout="30" stateConnectionString="tcpip=127.0.0.1:42424" />  ASP.NET State Service is started.   I got an error:  Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentContr...

Unable to make the session state request to the session state server #2
We have recently started receiving these errors in the event viewer. We are using the out of proc state server on the same machine. The errors become more frequent, almost like it snowballs until users cannot work. System Info: Windows Server 2003 Standard SP2 , 4 GB of RAM, IIS 6.0, Asp.Net 2.0. What I know for certain: The state server is started and running Recycling the app pool nor restarting IIS fixes the problem Rebooting the machine DOES temporarily fix the problem. I changed the stateNetworkTimeout from 10 to 20 in webconfig and that had no effect. There is usuall...

Session variables vs. Session States
What is the difference and in what situations are they used. Thanks, Mattypee A session state (the state of your session) holds your session variables. If your session state expires (due to inactivity) then you lose your session variables...and any other info stored for that session. If you need to store USER specific information within a web app, then session variables are one(of several) ways to do it. MajorCatsMajorCats Is there any code that you could show that would give an example? Thanks, Mattypee example of what? reading and writing session variables? ...

Unable to make the session state request to the session state server
 We have a web application in our school called CHECM. We are experiencing a high volume of ASP.NET State Server errors throughout this month. These errors have been occurring since 7/11/2006.   Our Session State Mode has been --------------------------------------------------------- <sessionState mode="StateServer" stateConnectionString="tcpip=CHECM:42424" timeout="20" stateNetworkTimeout="30"/>     Here is the Error we get randomly Exception: System.Web.HttpException Message: Unable to make the session state request to the session state server. P...

Visual Studio 2005
 Hi, I have recently been given a PC with Vista on it, and installed Visual Studio 2005 pro. I then moved a ASP.net web project from an XP machine to the Vista one. When I run the project from inside Visual Studio (debug mode) everything works fine on the front end of the website, but if I try and log in I get the following error:  Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that i...

Session State Variables across multi sessions
I am having an issue where I save my DataTable into a Session Variable:   Session["dtDMFile"] = dtDMFile; Different users can use the web form that I created. Once the data is loaded,I send the DataTable to the session variable. My problem is that when I go to reload the data in the table, it is taking the data from the last user who stored the DataTable instead of from the particular user on their browser. For instance, User 1 (machine 1) loads data with field contents of: field1  field2  field3 User 2 (machine 2), then loads data with field contents of: f...

Error message
Hello,I have developed an ASP.NET c# application.I have a "Reports" page in which i put the the report's DataTable in a session (to use it later on for paging and sorting).This works on my localhost but on production I get the follwong error:Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Servic...

Session lost every request
I lost the session in my web application after every request. I 've done breakpoints into Global.asax: With every request the following methods are called:Application_Start, Session_Start, Session_End and Application_End and I can't find the reason for that. Web.config: sessionState mode="InProc" cookieless="false" timeout="60" machine.config: sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" stateNetworkTimeout="10" sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI" cookieless="false" timeout="20" ...

Good news for those of you who get "Unable to make the session state request to the session state server." error..
Dear all,Due to the known problem of session variables getting lost if using InProc-server during frequent changes in development, I had to choose between SQL and ASP.NET State server, so I opted for the second. Initially, all fine, but after using it for a few days, I started to get this error: Server Error in '/cv2' Application.Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that it accep...

The page requires session state that is no longer available. Either the session has expired, the client did not send a valid session cookie, or the session state history size is too small. Try increas
Hi.. I am making a mobile application using .net framework 2.0. My Application has  web farm scenario so for state management  I am using Sateserver in my application. My application runs fine if I dont use web farm scenario But in case of web farm scenario it is giving me error "The page requires session state that is no longer available. Either the session has expired, the client did not send a valid session cookie, or the session state history size is too small. Try increasing the history size or session expiry limit."   &...

Web resources about - Session variables are lost with every request even though session persists - asp.net.state-management

Variable - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Westpac interest rate rise is one of many variable loan rate rises
WESTPAC is not alone in hitting its owner-occupier customers with a surprise interest rate rise, as dozens of other variable rate home loans ...

Airbnb upgrades variable pricing tool for hosts
Online home rental group Airbnb is rolling out an upgraded variable pricing tool that automatically raises or cuts room rates based on supply ...

Commonwealth Bank raises variable home loan rates
Home owners' mortgage costs are set to rise by hundreds of dollars a year, after the Commonwealth Bank became the latest bank to hike interest ...

CBA lifts variable home loan rates to offset costs associated with stricter capital requirements
The Commonwealth Bank to lift its home loan interest rates independently of the Reserve Bank to partially offset costs associated with stricter ...

Washington Square Signs Spielbergs, Choi Joins Variable and More
... films and an episode of the HBO comedy series "Girls," on which he plays the role of Ray Ploshansky. New York-based creative collective Variable ...

YouTube v10.32 Tweaks Some Interface Elements And Includes Hints About Virtual Reality Content And Variable ...
Forget Update Wednesday! Monday is the new big day. Not only were we treated to the latest M preview release and the official Marshmallow name, ...

"You have to ignore many variables to think women are paid less than men. California is happy to try." ...
Writes Sarah Ketterer in The Wall Street Journal in "The ‘Wage Gap’ Myth That Won’t Die" (which you can get to without subscribing if you Google ...

Staley: 'A lot of different variables...been a hard year'
... 41° Navigation Home Giants A's Sharks Warriors Kings 49ers Raiders Quakes Insiders More Tickets Shop Watch Staley: 'A lot of different variables...been ...

Expert Reveals the Latest Variable Capacity Technology
Learn about gForce Ultra CRAC equipment, the latest variable capacity technology to lower energy usage and increase reliability.

Resources last updated: 12/29/2015 2:20:25 PM