Why would Session_Start keep reloading without firing Session_End - asp.net

I am having trouble tracking down why the session keeps restarting in a web app.
I have placed code in both the Session_End or Application_End procedures to try and track what is happening, but neither of these two procedures are reached in code before the session restarts and fires the Session_Start procedure again.
Does any know what would cause the Session_Start procedure to restart without firing the Session_End or Application_End procedures?
Basically, there is code in the Session_Start that sets session variables and code in the Session_End that tries to log why the session ended
There are 100 or more aspx pages with VB code behind them all on the web site, and it looks like the session restarts randomly, sometime up to 3 times while loading the home page. I have a break set in the global.asax page inside the Session_Start procedure and it breaks there so I can tell when it reloads and loses all the session variables set in any of the ASPX page code behind.
I know some common causes like writing to certain files or folders like the App_Data folder, and the app pool being recycled, but I can not seem to track down why this is happening when Session_End or Application_End never fire and I cannot log the reason it ended.
I inherited this "project" and I "winging" my way through the code at this point so thanks you for any help you can give me on this ...
the server is IIS7, running ASP.NET and the code is in VB.NET, I have also included ' sessionState mode="InProc" ' in the web.config file to make sure the session procedures will be used.
This is VB code in the Session_Start procedure
HttpContext.Current.Session.Item("SessionMessageView") = "no"
HttpContext.Current.Session.Item("DefaultMenuName") = "Default"
HttpContext.Current.Session.Item("RootVirtualPath") = "/"
HttpContext.Current.Session.Item("BlockerTested") = False
HttpContext.Current.Session.Item("BlockerTurnedOn") = False
HttpContext.Current.Session.Item("IsMobileBrowser") = False
This is VB code in both the Session_End and Application_End procedures
Dim runtime As HttpRuntime = DirectCast(GetType(System.Web.HttpRuntime).InvokeMember("_theRuntime", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.[Static] Or System.Reflection.BindingFlags.GetField, Nothing, Nothing, Nothing), HttpRuntime)
If runtime Is Nothing Then
Return
End If
Dim shutDownMessage As String = DirectCast(runtime.[GetType]().InvokeMember("_shutDownMessage", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.GetField, Nothing, runtime, Nothing), String)
Dim shutDownStack As String = DirectCast(runtime.[GetType]().InvokeMember("_shutDownStack", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.GetField, Nothing, runtime, Nothing), String)
If Not System.Diagnostics.EventLog.SourceExists(".NET Runtime") Then
System.Diagnostics.EventLog.CreateEventSource(".NET Runtime", "Application")
End If
Dim log As New System.Diagnostics.EventLog()
log.Source = ".NET Runtime"
log.WriteEntry([String].Format(vbCr & vbLf & vbCr & vbLf & "_shutDownMessage={0}" & vbCr & vbLf & vbCr & vbLf & "_shutDownStack={1}", shutDownMessage, shutDownStack), System.Diagnostics.EventLogEntryType.[Error])
If I could only figure out why the Session_End procedure is not firing while the Session_Start procedure fires multiple time I might be able to track down the why the session is restarting.

See this question regarding Session_Start : Session_Start firing multiple times on default ASP.NET MVC3 project
Note that Session_End will never run if you are using SQLServer session state storage, or indeed anything other than InProc mode in your web.config sessionState directive.

With help from James I have discovered the problem. New code was added to determine if the user's browser accepts cookies and then it was being tested with cookies disabled. When cookies are enabled this does not happen and the session does not restart. It seems that when cookies are not accepted by a browser, and you try to store a cookie on that browser, it caused the session to restart because of the error without firing End_Session!
Now I guess we will have to rethink the cookie test and figure a way to store a flag that is somehow linked to the user and can indicate if cookies are accepted without trying to store a cookie on the user's machine ... hmmmm
Thank you all for your assistance on this ... sometimes it's the small things that trip you up ... I am reminded of the saying that an increase in bugs is proportional to changes in code

Related

Session in ASP is not storing values

I have two asp pages in the first page named verify.asp i have write this code:
verify.asp
<%
Username = Request.Form("loginx")
Password = Request.Form("passx")
liberado
Session("liberado") = Username
%>
in the second page i try to use the session variabel "liberado" with any result
barra.asp ,
<%
response.write(session("liberado"))
%>
What i'm making wrong? I m using chrome on IIS of windows 7, Username and Password have values
There was nothing really wrong with your code. Although I can see you've edited it now to remove the dim from liberado, but you've left liberado behind. This means your ASP will try and call a sub called liberado, which presumably doesn't exist. You can go ahead and remove that line.
<%
Dim Username, Password
Username = Request.Form("loginx")
Password = Request.Form("passx")
Session("liberado") = Username
%>
Trying to set a session whilst the session state is disabled will probably result in an error of some kind (and you didn't mention an error in your question). But make sure it's enabled by opening IIS and under ASP > Session Properties set "Enable Session State" to "True".
If it's already true then chances are there's something wrong with your form and the data isn't being posted. On your verify.asp page try running the following code:
for each item in request.form
response.write item & ": " & request.form(item) & "<br>"
next
This will output a list of all the form data being posted.
This could also be a cookie issue. If you're blocking cookies from being set in Chrome then there won't be an ASP session cookie, so session values won't be accessible as you move from page to page.
In Chrome press F12 to open developer tools, click the Applications tab, and from the "Cookies" drop down menu select your domain. Check there's an ASPSESSIONID cookie present, and it's the same cookie on both your ASP pages.
Check the application pool settings in IIS. If there are multiple worker processes active under "maximum worker processes", sessions don't always work. Sessions are stored per process, do if a different worker process handles the second request, the session from the first request might be missing. A setting of "0" means IIS uses as many processes as needed.
More information here

Classic ASP dumping Session Variables (WITHOUT Authentication)

I have inherited an Classic ASP Site and a "bolt-on" ASP.NET site...
NEITHER are using Authentication, BOTH sides have a manual "reinvent-the- wheel" (hard-coded) security system that validates the user/pw from a SQL 2000 database (i.e. "if the user is found via a SQL SELECT, let them in").
New development is in ASP.NET... and they have "integrated" the two sites via ONE login (described above) on the Classic ASP side... then passing a GUID (saved at the time of login to the users record) they validate the GUID on the ASP.NET side ("yes, this is the correct GUID, therefore this is my user... let them in").
Up until now this has been working ONE DIRECTION (Classic ASP to ASP.NET) only with no issues.
(Getting to the problem, bear with me...)
Now they want to perform the same basic design from ASP.NET to Classic ASP by updating the GUID, passing it back, where the lookup validates the user, send them to the correct Classic ASP page... (so the user can return to the Classic ASP side without re-loging-in, previously required) HOWEVER...
***HERE's THE PROBLEM
Session("UserID") is used on the Classic ASP side to (hard code) validate the user... then Response.Redirect is run to send them back to the page that they previously left via "sRedirectToString" ...
'user is found in DB, so send them to the correct page...
Dim sRedirectToString = 'the correct url
Call Response.Redirect (sRedirectToString)
HOWEVER, Session("UserID") gets cleared by IIS or IE (dun'no) and the (hard-coded) validation fails because Session("UserID") is NULL (blank)
Here's the simple (only) validation:
If Trim(Session("UserID") & "") = "" Then
'Session timed out
Response.Redirect('the denied page)
Else
Response.Write "<meta http-equiv=""X-UA-Compatible"" content=""IE=EmulateIE7"">"
End If
So, why are the Session Variables being cleared by a Redirect? (there is no other system authentication is being used).
There is no Session.Abort, nor any specific coding that is clearing Session("UserID").
But when Session("UserID") is tested (see code above) it is found empty and redirects to the DENIED.asp page.
So, hoping there is some property like "PersistSessionVariables" (or something) that I can set so they don't clear...
BUT THEY DO INDEED CLEAR IMMEDIATELY AFTER THE REDIRECT AND THIS IS CONFUSING TO ME.
I appreciate all the Wizards help!

Handle session timeout in asp.net using Javascript

Essentially I want to be able to catch when a user lets their session timeout and then clicks on something that ends up causing an Async postback. I figured out that if I put this code in my Session_Start (in Global.asax) then I can catch a postback that occurred during a session timeout:
With HttpContext.Current
If TypeOf .Handler Is Page Then
Dim page As Page = CType(.Handler, Page)
If page IsNot Nothing AndAlso page.IsPostBack Then
'Session timeout
End If
End If
End With
This works fine. My question is, I would like to be able to inject some javascript into the Response and then call Response.End() so that the rest of the application does not get finish executing. The problem is that when I try Response.Write("<script ... ") followed by Response.End() then javascript does not get written to the response stream. I'm sure there are other places in the application that I can safely write Javascript to the Response but I can't let the rest of the application execute because it will error when it tries to access the session objects.
To sum up: I need to inject javascript into the response in the Session_Start event in Global.asax
Note: You may be wondering why I'm not doing this in Session_End...we don't use InProc sessions and so Session_End doesn't get called...but that's beside the point...just wanted to make it clear why I'm doing this in Session_Start.
Writing to the response stream outside of an HttpHandler is generally not a good idea; it may work in some corner cases, but it's not how things are intended to work.
Have you considered using either a Page base class or a Page Adapter to do this? That way, you would only need one copy of the code, and it could be applied to either all pages or just the ones you select.
Another option would be to use URL rewriting to redirect the incoming request to a page that generates the script output you need.

Cookies NULL On Some ASP.NET Pages (even though it IS there!)

I'm working on an ASP.NET application and I'm having difficulty in understanding why a cookie appears to be null.
On one page (results.aspx) I create a cookie, adding entries every time the user clicks a checkbox. When the user clicks a button, they're taken to another page (graph.aspx) where the contents of that cookie is read.
The problem is that the cookie doesn't seem to exist on graph.aspx. The following code returns null:
Request.Cookies["MyCookie"];
The weird thing is this is only an issue on our staging server. This app is deployed to a production server and it's fine. It also works perfectly locally.
I've put debug code on both pages:
StringBuilder sb = new StringBuilder();
foreach (string cookie in Request.Cookies.AllKeys)
{
sb.Append(cookie.ToString() + "<br />");
}
this.divDebugOutput.InnerHtml = sb.ToString();
On results.aspx (where there are no problems), I can see the cookies are:
MyCookie
__utma
__utmb
__utmz
_csoot
_csuid ASP.NET_SessionId
__utmc
On graph.aspx, you can see there is no 'MyCookie'
__utma
__utmb
__utmz
_csoot
_csuid ASP.NET_SessionId
__utmc
With that said, if I take a look with my FireCookie, I can see that the same cookie does in fact exist on BOTH pages! WTF?!?!?!?! (ok, rant over :-) )
Has anyone seen something like this before? Why would ASP.NET claim that a cookie is null on one page, and not null on another?
This was happening because I was running the app under a different virtual directory. When I ran it on the original one, it worked.
I would suggest loading the IIS debug diagnostics tools. It is entirely possible that on that particular server there is a resource problem or unhandled exception that is killing that particular cookie AFTER it is added to the response but before it is flushed to the user. This is basically caused by a series of exceptions that occur in rapid succession causing rapid fail protection to shut down the w3wp.exe process that your page is running under. When the process is spooled back up to feed the response, the cookie is gone and all that goes out is the rendered html.
You might also try turning off rapid fail protection or altering memory settings/recycling settings on the application pool.

Forms authentication failed for the request

I have a web application using cookieless forms authentication. Every day my event log has a ton of 4005 error codes (Forms authentication failed for the request). I believe this is happening because users are bookmarking pages while they are logged in so when they revisit the forms ticket in the url has expired, atleast this is the only scenario I can trigger in testing.
My question is it possible to disable logging for this 4005 code ? its filling up my event log
You can handle the error so it does not appear in the log
'in global.asax
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim lastError As Exception = Server.GetLastError()
' Must be a better way, just can remember how, you will get the idea.
If lastError.Message.Contains("Forms authentication failed for the request") Then
'do nothing
Server.ClearError()
End If
End Sub
If you can use cookies, its a much better solution than cookieless mode because your users will get to use bookmarks, which they'd surely expect to be able to do, and your error log will not be filled with errors. Its also less vulnerable to session hijacking.
Not an answer to your question, and I'm not even familiar with ASP. But if, just like for example PHPSESSID and jsessionid, this "forms ticket in the url" is actually a session id that is also added to the URL for anonymous visitors, then maybe search engines can cause this error as well? And if so: doesn't that break your search scores?

Resources