In my Web Application, i am getting an error. "Session state has created session ID. But It can not save it because it was already flushed by application".
I googled for this issue and found that i have to store session id in Global.asax Session_Start Event.
string id = Session.SessionID;
But it was already exist in my application. I am not sure what else is causing issue. I was not using Response.Flush() also.
Can anyone please explain about this issue & fix for it.
That happens because sometimes (depending on the web.config configuration) the SessionID is not set in the cookie when Session_Start event executes in the global asax.
You encounter this error because at somepoint in the pagelifecycle a variable is set in the session. After the request ends, ASP.NET tries to set the SessionID too, but if the Request was flused (eg. this can be done by Response.Write or AJAX itself flushes the response) this exception will be thrown.
A simple fix would be (in the global.asax file):
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
//Ensure SessionID in order to prevent the folloing exception
//when the Application Pool Recycles
//[HttpException]: Session state has created a session id, but cannot
// save it because the response was already flushed by
string sessionId = Session.SessionID;
}
Related
My session variables are being lost between pages. Interestingly, this seems to be environment-specific - in our production environment, this works fine, in our test environment, we lose the session variables. This previously used to work in our test environment with the same code, which leads me to believe it's some IIS or server setting that's different.
This is an integration to SFDC where I am adding some session variables on page load. Then, after a user goes through a login flow, SFDC calls back and I try to read those session variables.
Here's how I set the session variables:
Session.Add("tenantID", tenantId);
Session.Add("clientID", tenantInfo.SalesforceKey);
Session.Add("session", session);
Session.Add("clientSecret", tenantInfo.SalesforceSecret);
Session.Add("userEmail", user.Email);
Logger.Debug("Set session tenantID to " + int)Session["tenantID"]).ToString()); // This outputs the proper value.
However, in our callback function in the same controller, when running this code, all session variables are null.
public ViewResult Callback(string code)
{
Logger.Debug("Entering callback, code:" + code);
Logger.Debug("Session vars:");
if (Session["tenantID"] == null) // This is true
Logger.Debug("tenantID: null");
if (Session["clientID"] == null) // This is true
Logger.Debug("clientID: null");
if (Session["session"] == null) // This is true
Logger.Debug("session: null");
if (Session["clientSecret"] == null) // This is true
Logger.Debug("clientSecret: null");
// etc...
}
Initially I thought session was being ended, so I added the following in Global.asax. There's no session ended log line output until well after the callback executes.
void Session_End(Object sender, EventArgs E)
{
// Clean up session resources
Logger.Info("session ended for " + (string)Session["userEmail"]);
}
void Session_Start(Object sender, EventArgs E)
{
// Clean up session resources
Logger.Info("session started.");
}
Some clues that might help here:
- I ran a fiddler to capture the initial page load and the callback, and the ASP.NET session ID was the same in both requests:
(Page Load): Cookie: ASP.NET_SessionId=j1ggxuamkc2rk3q03z2vwye1
(Callback): Cookie: ASP.NET_SessionId=j1ggxuamkc2rk3q03z2vwye1
Previously, our logger statements would output to one file, however, we use log4net, and it now seems to be creating a second file to output the callback logger statements. In production, we only see one file. If I get a session end log from the Global.asax code in the first file (associated with page load), I can read the session values. If I get a session end log in the second log file (associated with callback), the session values are null again.
My web.config does not have any sessionState element included, and this is set the same across production and test.
Thank you for your help.
Here are the IIS Session State settings for that web application:
Session State Mode settings: Set to In Process
Cookie Settings: Mode: Use Cookies
Name: ASP.NET_SessionId
Time-out: 20 minutes
Regenerate expired session ID is unchecked
Use hosting identity for impersonation is checked
Compare the settings for the application pools between the test and prod environment.
I have also similar situation where our application runs fine in server and not in local due to session variable null. If you are implementing sessionfilter in MVC, it is better to run the application in IIS Express in visual studio instead of visual studio development server. That solves our problem of session loss.
I am working on a asp.net web project in which if I use
in web config
then the encrypted sessionId is visible in URL but if I change cookieless to false then encrypted sessionID get removed from url but I receive a new session.sessionId on each request
Please help so that no encrypted session.sessionID is visible in url and also there should be SINGLE session.sessionId on every request.
If you are using cookies based session management ASP.NET is using some optimalization which results in creating new session every time until there are some actual session data to store. To avoid this you can put a dummy value into session in Session_Start event available through Global.asax:
protected void Session_Start(object sender, EventArgs e)
{
Session["DUMMY_KEY"] = "DUMMY_VALUE";
}
This way the session id will remain the same until the session time out occurs.
In my page I'm regenerating session id on every button click to go to the next page. I've already saved username in my session variable (session["uname"]=txtusername.text) in the time of log in. But as I'm regenerating new session id ,session["uname"] is having null reference because of new session id.That's why I want to set the session variable value using a Global.asax in session start function.
void Session_Start(object sender, EventArgs e)
{
session["uname"]=here;
}
But here in Global.asax page I'm unable access any value from my log in page..
The main problem is accessing any value in global.asax from code behind.
How can I solve this......Plz help......Thanking in advance..............
HttpContext.Current.Session["uname"]=here;
First don`t write business logic in Global.asax .
I want to point you out 3 basic things:
When session_start() called
How sessions are maintained
Where you should set your session variables.
For the following details I am assuming you have login.aspx, login.aspx.cs:
As you know HTTP is stateless protocol, so every request is new request.
So for every request session_start() will get executed.
When user request the resource for the first ever time, unique session will be generated, and cookie containing session Id will be sent to client.
For any further request from the user, HTTP client will pass the cookie to server, so user can be tracked by the server. This is how session works.
Now lets come to your code you are setting Session["uname"] in session_start() of Gloabl.asax, keep in mind that Globlax.asax is called before the page life-cycle begins
so it does not have access to page data.
Instade you should set your Session["uname"] in login.aspx.cs file. Here check if users credentials are correct then:
set Session["uname"]=value.
Now for every other request Session["uname"] for that user will be available. And you can also retrieve/update the values at session_start() of Global.asax too.
I want to read session id in application error event but always get error "Session state is not available in this context". Why? The strange thing is that I have the same code in another asp.net app and everything works fine.
void Application_Error(object sender, EventArgs e)
{
var sessionId = Session.SessionID;
//skipped code
}
The session object may not be available this is dependent on when the error occured.
For example if an error occured on Begin_Request the session would not be available as it has not yet been created.
So in summary sometimes it will work sometimes not, depending on when the error occured.
Best to check the state of the session object before accesssing the session id e.g.
HttpContext context = HttpContext.Current;
if (context != null && context.Session != null) ...
check if any event missing in c# which is mapped to a control or issue in design part
Application_error can fire in situations where a session is not present, for example when the garbage collector cleans up. The source of the error may not have been a user thread.
Just check whether session is null first.
Simon
You may get this error if you are using an Out-of-Process state mode for ASP.NET state server. You need to mark any classes you wish to save to session state with the [Serializable] attribute
I need unique session id but each it's new unless you write something in it.
The fix looks like this Session["stubkey"] = "fsdufhusd" in page load method.
It's pretty odd to me. Is there any way to init session or probably I do something wrong with configs?
thanks in advance.
The SessionID documentation recommends the same work-around you're using:
When using cookie-based session state,
ASP.NET does not allocate storage for
session data until the Session object
is used. As a result, a new session ID
is generated for each page request
until the session object is accessed.
If your application requires a static
session ID for the entire session, you
can either implement the Session_Start
method in the application's
Global.asax file and store data in the
Session object to fix the session ID,
or you can use code in another part of
your application to explicitly store
data in the Session object.
You don't need to initialize the session on page_load. You can initialize the session on Global.asax like this
protected void Session_Start(Object sender, EventArgs e)
{
Session["init"] = 0;
}