Monday, March 12, 2012

ASP.NET Exception: "Session state has created a session id, but cannot save it ..."

Symptom:
  • Only happens for new session
  • Exception Message:
    A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll Additional information: Session state has created a session id, but cannot save it because the response was already flushed by the application.
  •  Stack Trace: 
[HttpException (0x80004005): Session state has created a session id, but cannot save it because the response was already flushed by the application.]   System.Web.SessionState.SessionIDManager.SaveSessionID(HttpContext context, String id, Boolean& redirected, Boolean& cookieAdded) +3691007   System.Web.SessionState.SessionStateModule.DelayedGetSessionId() +199   System.Web.SessionState.SessionStateModule.ReleaseStateGetSessionID() +25   System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +874   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270 

Cause:
  • I was able to narrow down the cause of this problem to setting page's Buffer="false"
  • Reasoning would be that without buffering, all content are pushed to client immediately, and somehow, ASP.NET decided to set cookie at a very late stage where it can no longer write to HTTP header to set SessionID cookie
Solution:
Set Buffer to true is not a solution for me, because I will need to flush content to deliver real-time progress information.
Based on some understanding, a solution quickly came up with some Google search. Simply add the following line to Global.asax.cs > Session_Start, the problem is resolved.
string sessionID = Session.SessionID;