Session being reset inadvertently - asp.net

I have a legacy ASP.NET application. It was converted from NET 2 to net 4.
It uses state server session.
At some point, the app opens a new page (in a new browser tab: link target = "_blank")
But after returning to calling page (tab), I discovered the session is reset, so current user is no longer used and app redirects to login page. Actually, SessionID remains unchanged, but IsSessionNew is set to true, and session has no variables set in it.
The app doesn't use Session.Abort or Session.Clear.
Even if I change session to InProc, and change the target for the links to _top, or _self, or remove entirely, the same thing happens - session got reset.
This is session setting in web.config (alternatively I used StateServer, but with same result)
<sessionState timeout="432000" cookieless="UseCookies" mode="InProc"/>
Any idea what can cause this?
Thank you.

I finally fixed the problem.
However, I didn't found the actual cause, but I found the module which caused the issue.
It was a aspx page which did 1001 things (it's basic functionality plus another approximatively 80 other things based on ajax calls (!!!). I didn't made that page !!!
But the part that caused the problem was a functionality that served an image file.
So I rewrite that part as an ASHX handler, and then the code worked ok - the session remained open.

Related

White screen issue, if an user stays idle in an asp.net page

In our ASP.NET website one of the page has some tabs in it. Each tab represents different content and moving from one tab to another reloads the entire page. If I'm currently in one of the tab and stay idle there for around a minute or more and then move on to an another tab, only a white blank screen comes up.(with no page source code info for that in the browser).
Sadly this same issue is not at all reproducible for the same website in lower testing environment. Issue is occurring only in Production version of the website.
Is there an IIS setting or web.config setting which I should change to resolve this issue. As I believe the source code of the concerned webpage wouldn't be a reason.
This is probably because the session timeout has reached the limit ending the session.
You have three possible solutions in this case:
First
You can try editing the web.config file located on the root of your application to extend the session timeout. Try something like this:
<sessionState mode="StateServer" timeout="500">
</sessionState>
According to MSDN you can set timeout up to 525,601 minutes (1 year).
Second
If it doesn't work and you have access, you can try editing the timeout on IIS:
Open the IIS, click on the Application Pools, Select the Application
pool for your application.
Right Click on that, Select Properties.
In the Performance tab, Set the idle timeout as your desired minutes
for "shutdown worker processes after being idle for ..... minutes".
IMPORTANT: Apart from this you have to set the timeout in web.config as said above.
Third
You can create an ajax function to be executed in background, preventing the session from expiring:
function keepSessionAlive(mod) {
mod.open("GET", "blank.html", true);
mod.onreadystatechange = function() {
if (mod.readyState == 4) {
document.getElementById("#blankDiv").innerHTML = mod.responseText;
}
};
mod.send(null)
}
setInterval('keepSessionAlive()', 100000);
That's it. Hope it helps.
Are u usin any custom http module? Can we have a look at the page souce aspx and code behind? It happened to me when i used elmah but in quite different scenario.
Other may be due to the session thing that other pointed out. Hope that helps.
I would open the chome dev tools or firebug if in firefox. If in firebug, I would go look at the net and console tabs and see what's actually happening from a network perspective. It should be easy to look at the traffic in dev and compare to production. I'm guessing they aren't the same, and it would instantly point you in the right direction.
Fiddler is also an option if you want to watch the traffic as if you were a middle-man.

URL Rewriting Postback with ViewStateMac Enabled

Using: Visual Studio 2010 with ASP.net 4.0
I have a website which uses URL rewriting and I want to keep the rewritten URL on Postback. I've read a lot of the topics on this subject and I still haven't been able to figure out if this is possible.
For example:
http://localhost/ActualPage.aspx?PageID=4
Is rewritten as:
http://localhost/member/forum.aspx
The page contains a number of controls which use a Postback (for example a Telerik RadGrid with sorting and paging). Normally when the postback takes place the browser is redirected to the unrewritten url - the address bar shows /ActualPage.aspx?PageID=4 etc. In this scenario everything works correctly.
However I want to retain the rewritten URL after the postback, so I have coded to change the Form.Action property to be the rewritten URL like so:
Page.Form.Action = "/member/forum.aspx"
Now the page correctly retains the URL in the address bar but throws a "Validation of viewstate MAC failed" error when the postback occurs - which I would expect it too as the viewstate originated from a different URL.
Strangely this problem occurs even when enableViewStateMac is set to false (either in the page or in the web.config) - but I don't want to disable this anyway.
Effectively I think what I need to do is tell the page / viewstate mac authorisation that is it ok to accept input from this alternative URL but I can't find anyway of doing this. I've tried different URL rewrite system to see if that makes a difference, and i've tried added a generated machineKey - neither of which has made any difference. Is there any way of doing this?
In short I want:
Rewritten page with postback going to the rewritten URL
ViewStateMac enabled
No viewstate validation errors
I remember in earlier versions of .NET using a .browser file with FormRewriterControlAdapter but this doesn't seem to make any difference in .NET 4 (I don't remember if it successfully retained the URL anyway).
I have found a solution - it turns out the problem was actually unrelated and masking itself as a ViewStateMac issue.
Previously I had been redirecting all the URLs to one page, doing a database lookup and then using Server.Transfer() to deliver the correct page to the browser. The real problem was being caused by using Server.Transfer() - which it seems is recognised by Microsoft to be an issue when working with the viewstate.
I have made adjustments so IIS performs the database lookup, the entire rewrite and therefore Server.Transfer() is not used - and the original problem I had has been resolved.

"Validation of viewstate MAC failed. If this application is hosted by a Web Far..."

i am facing the dreaded:
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Error.
Ok so i looking it up and found that it can be caused by two things, viewState which can not be verified by the page, and/or events that can not be validated.
I put
<pages enableEventValidation="false" enableViewStateMac="false" viewStateEncryptionMode="Never">
In my web.config to stop the problem, but that hardly seems like a fix to me.
The thing is, i never even used viewState in my application. I know that asp.net uses viewstate by default to store some things, but i doubt the default values stored here will cause any errors.
I noticed that the problem seems to happen when i postBack and the page has not finished loading yet.
Thanks
Edit: Please, can someone test my website www.vittoriosaStarsNursery.com and see if you get the error i got above? I dont get it locally but people keep telling me they are getting it.
Isnt this just a case of putting a one liner in your web.config
<machineKey decryptionKey="A4B12CCDD50E95F8GB9GFH6JKAT4Y0U0I2OF2DF2AAFE5AB46189C,IsolateApps" validation="AES" validationKey="480CDF2AS9S9AS5CFDGF0GHFH9JJH4KHKAKLJ2L9F3SAS82A6C16911A29EF48903783F94529C21570AACB72766FB38CD4CE7B85B0ACE3149DC5FC1CCF1AA1CECE3579659996593B06,IsolateApps"/>
One thing I have come across that causes this issue has to do with the recycling intervals of the app-pools on the webserver.
I found this by looking at the event information in Eventviewer/Application logs and the "Task Category" called "Web Event". Then for the time period that this event took place I looked to see if there were any recycled events that took place just before that (Eventviewer/System logs and the "Source" called "WAS".
By default an app-pool will recycle every 1740 minutes (29 hours). If this recycle happened while a user is busy on the site and send post back to the server, the server no longer recognizes the session/viewstate and rejects what is being posted back.
To overcome this from our perspective is to set the recycle event to happen at a specific time of the day when we don't expect activity on the site. In our case 3am in the morning.
Hope that helps someone out there.
You're not going to like my answer. This error is basically unavoidable in webforms. My solution was to leave webforms for MVC3 and razor.
I noticed that the problem seems to happen when i postBack and the
page has not finished loading yet.
this is one of the easiest ways to cause this error. In ASP.NET 3.5 (or 4.0) there's a setting that you can make sure viewstate gets loaded very early in the page to try to help diminish it. It still doesn't solve it.
Chunking the viewstate doesn't solve it.
There is just something inherently wrong to the way webforms works that this error will plague your application at random times forever.
At my site, this meta tag were causing the error:
<base href="http://www.SITEURL.COM" />
I have a dropdown, I update on another dropdowns changed selection. So when the postback happened (dropdown #2 changed index), I got the exception.
I've tried everything else from applying machinekey to web.config and setting theese attributes at the page
EnableViewState="false" EnableViewStateMac="false"
I am using VS 2010 against a Windows Web Server 2008 and what I eventually found was that I had two keys set for the same service in the appSettings section of webconfig. I went to IIS and checked the Application Settings on the virtual directory and got an error, fixed it in the WebConfig and the problem resolved. I did create a machine key but that did not fix the problem. Nor did the
pages (...) validateRequest="false" enableEventValidation="false"
enableViewStateMac="false" viewStateEncryptionMode ="Never"/
Settings. FWIW ...
I used this Microsoft article to create my own machineKey validationkey and decryptionKey. As others have stated, this can be placed within the system.web section of web.config, though there are security concerns if other people get hold of the key.
Well, yes i suppose disabling encrypted viewstate solves the problem but i have never tested it nor do I advise it. Viewstate stores the state of controls and is also very convenient for storing persistent variables.
Take for example you work for a garage and have a list of jobs. You go to a page that lists the jobs. Now you click a job which goes to another page appending the jobid (eg. job.aspx?id=1). On that page, there is a checkbox which marks the job as complete. Once you tick that checkbox, it posts data back to same page and writes to the database that the job is complete. But how does the server know which job to mark as complete because you have only posted back true or false from the checkbox. However, if the first time you load the job details page you record the job id in Viewstate, then when you post pack the checkbox, you can read in the jobid from the viewstate.
Why is it not good to use unencrypted viewstate?
Imagine what the server has to do to mark the job as complete. It probably has to run an sql command to update the database. Something like UPDATE jobs SET completed=GETDATE() WHERE id=1.
If your viewstate wasnt encrypted and i could add my own job id, I would put something like '; DELETE FROM jobs;' which would then cancel out the initial UPDATE command and delete ALL your jobs... not very good for the garage :)

Session_Start firing multiple times on default ASP.NET MVC3 project

I think I may have found a problem with ASP.NET MVC and it's event pipeline. In particular, I am finding that Session_Start is being called multiple times, each containing a new SessionID.
Here's the step-by-step process:
Open VS2010
File | New Project
ASP.NET MVC 3 Web Application, accept default name, click OK
Select Internet Application (although I don't think it matters really), click OK
When finished creating, edit the Global.asax.cs file
Add the following method (yes it's empty):
protected void Session_Start()
{
}
Set a breakpoint in the method
Debug
Notice that the breakpoint is caught twice before displaying the page. If you watch "Session.SessionID" when the breakpoints are caught, you will see that the session id is new each time.
Once you get to the home page, click on the "Home" or "About" tab link.
Session_Start will be fired again, this time with a new SessionID.
Continue execution, and any subsequent actions will no longer fire Session_Start.
I tried the same thing on a standard ASP.NET Web Application (not MVC), and Session_Start only fired once.
I'm pretty sure I'm not doing something wrong here, as I am using the default project templates, and the only code that is being modified is the Global.asax.cs file, to add the Session_Start method.
I am using IIS Express, but I've repeated the above steps using the "Cassini" web server (Visual Studio Development Server), with the same result.
Any advice?
UPDATE
I decided to use Fiddler to inspect the HTTP traffic during my debug session. It seems that:
The first Session_Start is fired when I am requesting the "/" URL. This seems reasonable. The SessionID generated at that time is then written in the response to the browser. Again, seems reasonable.
Fiddler then shows requests/responses for the *.js and *.css files. All successes. None of those fire off Session_Start. Good so far.
Then Fiddler shows that a request has been made for "/favicon.ico". At this time, Session_Start fires, and generates a new SessionID... I continue.
On Fiddler, it shows that the "/favicon.ico" file was not found (404). The webpage is displayed. I click on the "Home" link.
The URL "/" is requested and response is OK in Fiddler. But then, another "/favicon.ico" file is requested, and again Session_Start fires with a new SessionID... I continue.
All subsequent requests have responses, and the browser stops asking for "/favicon.ico".
I made note of each of the three SessionID's generated, and it seems the one that the browser holds on to is the first one. So when we get to step 6 above, and everything seems to work, it's actually using the very first SessionID that was generated.
So... I decided to host a "favicon.ico" file. I placed the ico file in the root of the project, and started my debug session again. This time, Session_Start only fires once. "/favicon.ico" was served successfully (200).
So... I guess it is working the way it should in a sense... But why do calls to "/favicon.ico" fire off the Session_Start event???? Shouldn't I have the choice to NOT host a favicon?
ASIDE: I tried all the above in an ASP.NET (not mvc) project, and it did not have the same problem, even though there was no favicon.ico file hosted by a default "ASP.NET Web Application" project.
I kinda had this problem for a while, and finally I realised that it was because there was some http/https shenanigans going on... looks like it destroys and recreates your session if you flip the ssl around like that and you have
<sessionState mode="InProc" sqlCommandTimeout="3600" timeout="120" cookieless="false" />
<httpCookies httpOnlyCookies="true" requireSSL="true" />
Possibly a trap for new players or people who are really tired and not paying attention! :)
Just FYI in case this helps anyone...
I think I've come to a point where I have a couple of solutions (albeit both seem 'hacky' to me), so I think I'll accept these and move on.
Got a comment from #Tz_ above that mentioned I should ignore the route for the favicon file. That's essentially what I'll be doing. (kudos #Tz_!)
Came across the following post, (among others). It describes a problem that when the browser requests a "/favicon.ico" file from an ASP.NET MVC site, the MVC stack is mistakingly trying to look for and instantiate a controller. I'm wasn't sure if that was true or not for my situation, but the answer suggested adding the following route entry:
routes.IgnoreRoute("favicon.ico");
I gave it a shot (added the above), and that fixed it!
So, I still don't know why "/favicon.ico" request has a mistaken identity in MVC, but I know how to fix it in my situation. Either:
Host a favicon,
or add an ignore route entry.
Again, both seem like hacks to me, as I think this is something controller factories should be capable of handling gracefully. IMHO
Reason you are getting Session_Start firing each time is because you have <httpCookies requireSSL="true" /> in <system.web> in your Web.Config remove this and you are good to go.
I can't reproduce this problem. I've tested on ASP.NET MVC 3/Tool Update, Win08/R2/SP1 and Win7/SP1 using IIS 7.5, Cassini and IIS Express. I see the 404 favicon request in Fiddler, but the break point is not hit for favicon. I tested with IE9, the current FF and Chrome. Each time I hit the site with a new browser, Session_Start() is called and I see the new session ID. I work for Microsoft so I'd like to know how to reproduce this problem.
This happened to me when I had some <img> in my pages with a wrong "src" attribute. Putting a valid path in "src" solved my problem.

'System.Web.HttpContext.Current.Session' is null

I have an ASP.NET website that has been deployed since 2008 with plenty of users. From time to time, I've made updates to the site and uploaded those changes to the server without problems.
However, today, I'm trying to run the site on my development environment and I keep getting errors any time the code tries to access session state. It appears System.Web.HttpContext.Current.Session is always null!
Any suggestions on where to look? It's been a while since I worked on it and am not 100% sure if I've worked on it with the current version of ASP.NET (4.0).
Other than that, the code's been working fine and I haven't made any changes since it was last working.
More Information
I've spent all morning on this but I apparently have a larger issue.
If I step through the code, I see that my page Load handler executes. At this point, Session is not null. After that, my specialized master page executes. After that, my general master page executes. I then step through load events for a couple of controls. This all seems very normal.
Then, if I keep executing, suddenly I'm loading a specialized master page for another page and Session is now null!
If I hit F5, it the original page shows. But somehow it is causing the other page to load and without session state. If I turn off debug mode, it appears to run normally.
Obviously, I have something strange happening. I need to determine why the other page is being loaded.
Try to put a static page, something like Test.aspx and browse to that page. If it gets loaded, try to use Session property of the page in code behind. Do you still get the error? In that case, Session doesn't load. I suggest creating an HTTP Module and hooking into a method which is responsible for loading Session info. See what's wrong.
Just a guess - did you deactivate sessionState for any reason? Anything like this:
<sessionState mode="Off"/>
My apologies. The information I provided was completely misguided and was not sufficient to resolve the issue.
The problem was actually due to some custom error handling that redirected to an error page. This was configured in web.config. This error page was using the master page that my code was mysteriously executing.
Apparently, an error was occurring within the GridView control. This is ASP.NET code and not my own, so I was unable to step through it or catch it with a regular handler.
This was hard to understand. If I was executing the Load event handler of my error page, then it would've been obvious. But it appears to have skipped over that. Thus, my confusion.
Try checking the global.asax file or any other pre-load events and make sure the Session is not set to NULL explicitly.
Maybe your erring master page is calling code from some external class where the session object is not available?

Resources