ASP.Net Session data lost between pages - c#

I came across a weird behavior today w/ my web application. When I navigate from a page to another, I lose one particular session variable data.
I'm able to launch the app in firefox and able to see that the session data is not lost.
I use Response.Redirect(page2, false) to redirect to another page.
Below code was used to track session variables
System.IO.StreamWriter sw = new System.IO.StreamWriter(#"c:\test.txt", true);
for (int i = 0; i < Session.Count; i++)
{
sw.WriteLine(Session.Keys[i] + " " + Session.Contents[i]);
}
sw.Close();
Can anyone help me in this? Any help is appreciated.

I was having exactly the same problem and in my case I found the cause of this behavior. It turned out to be that when I was invoking the Response.Redirect() method I was using the full url instead of just the page name. So when I was in localhost/myapp/page1.aspx I redirected to MYMACHINENAME/myapp/page2.aspx and that's why the sessions were different for each page. I corrected this in my code using only "page2.aspx" and then the final url on any browser (IE, firefox) was localhost/myapp/page2.aspx.Don't know if you're playing with the urls the way I was doing it but maybe this answer can give you a clue. Thanks and good coding

Are you developing in a web farm / web garden environment?

Try using the state server mode. Depending on how your application pool is configured and your deployments the default in-process mode can be unpredictable.

My problem was as follows :-
Problem: When we have moved the ASP.NET application to an another server (Windows Server 2008 R2) with IIS 7.5, the application cannot move session values between the pages. e.g. the session value was set in first page but it could not move to next page. In next page, value for same session variable was coming NULL.
Session values was moving to next page in case of Google Chrome and Firefox but not in Internet Explorer.
Resolution: We have created URL name with "_" (underscore) e.g. http://MySite_test.com. After removing "_", it works as required e.g. http://MySitetest.com
Other Possible Solution:
Use Response.Redirect with having second parameter as "false" to avoid execution of page and thus to avoid lose session token. You have to use URL as follows. Response.Redirect("NextPage.aspx",false)
If the application pool of the site is configured as a web farm or a web garden (by setting the maximum number of worker processes to more than one), and if you're not using the session service or SQL sessions, incoming requests will unpredictably go to one of the worker processes, and if it's not the one the session was created on, it's lost. The solutions to this problem is either not to use a web garden if you don't need the performance boost, or use one of the out of process session providers.

Related

Check if a mobile device is requesting the desktop site

I'm using 51 degrees on my MVC site as an adaptive approach to serving my pages. All is working well.
I have recently added output caching and I use the VaryByCustom to check whether it is mobile or desktop:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
// this is for the output cache
if (context != null)
{
switch (custom)
{
case "Mobile":
return GetMobileCustomString(context);
}
}
return base.GetVaryByCustomString(context, custom);
}
private static string GetMobileCustomString(HttpContext context)
{
if (context.Request.Browser.IsMobileDevice)
{
return "IsMobile";
}
else
{
return "IsDesktop";
}
}
However I have run into a problem that if the first mobile user to browse the site has requested the desktop version, this will be cached for all mobile users.
I need to change the GetMobileCustomString to include a check for if it is a mobile requesting a desktop site. Is there any way to do this?
Update
As a bounty has been opened on this, I thought I would offer an update:
Firstly, it was not the first load causing the desktop page to be cached as I had initially thought, so having done a lot of searching, research and testing on this, I feel the desktop page should never be cached for the mobile version (if you are on MVC 5). I have stepped through the code when doing a mobile request and when it gets to the vary by custom, it shows context.Request.Browser.IsMobileDevice as false.
Not sure what is causing the desktop site to be cached for the mobile site - perhaps it is a hangover from the bug in MVC 4. It just seems to be random (ie, one day it will be fine and then another day it will be serving the desktop site for some reason) and recycling the app pool will always fix it.
I also found that I could get the overriden browser by using:
using System.Web.Wepages;
context.Request.RequestContext.HttpContext.GetOverriddenBrowser();
But it didn't seem to be much use
It seems to me like what you are doing should work, provided you are storing the cache at the client side.
You should be using the OutputCache attribute on your controller actions in the following manner:
[OutputCache(Duration = 5, VaryByCustom = "Mobile", Location = OutputCacheLocation.Client)]
(The duration is up to you)
That being said, browser detection is based on HTTP headers so nothing is going to help you if the requesting browser is sending headers for a different agent.
The other option is to use feature detection instead.
I hope that helps.
Within the 51degrees.config there is a setting
<redirect devicesFile="" timeout="20" firstRequestOnly="true"
This firstrequestonly may be confusing your caching system so treating the first mobile device as the first request, and all other mobiles as the same session of the original mobile device. Try setting this to false and see if that helps solve your issue.

Why IE Keeps sessions alive?

Hy all!
I'm developing a MVC 4.0 web application with C# and came accros the following error.
In major browsers (Chrome, Mozilla Safari, etc...) when i click logout in my web application it does the correct, logout the current user.
When i do the same operation on IE, dosen't work, i login with the new user, and IE keeps the last user until i press ctrl+F5.
The only thing i'm using for authentication is Sessions, nothing more.
Someone came acrros this issue? i've tried clear cache, clear sessions with abadon, clear, removeall and nothing seems to work when i'm on IE.
If you guys need some more info to help me with that, i'll answer as soon as possible!!
I've found the following works:
Session.Clear()
Session.Abandon()
Session.RemoveAll()
If Request.Cookies("ASP.NET_SessionId") IsNot Nothing Then
Response.Cookies("ASP.NET_SessionId").Value = ""
Response.Cookies("ASP.NET_SessionId").Expires = DateTime.Now.AddMonths(-20)
End If
Usually, browsers implement it so that ctrl+f5 means "make an http request for the current url, without the browser cache). So, no matter what you do after the fact in your server-side code, because IE is by default reloading the current page from its local memory without even hitting your server, you will not appear logged out. Then, when it does eventually go back to your server, it's still sending the same cookie because the page that would have logged you out is never actually hit.
One way to test if this is happening, is to set a breakpoint in your logout code. Refresh the page without holding ctrl in IE, and see if the breakpoint is even hit. If it's not, then you know client-side caching is the cause.
Workarounds:
This code on the server will send the page with metadata indicating the browser is not allowed, under any circumstances, to cache the page on their side:
response.Cache.SetAllowResponseInBrowserHistory(false);
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.Cache.SetNoStore();
response.Cache.SetExpires(DateTime.Now);
response.Cache.SetValidUntilExpires(true);
-- or --
When you go to your logout page with a link like this: /logout or /home?logout=1 add an extra paramter like this: /logout?cacheBust=123yt74y5t, making the last part random. This works because most browser caches will cache based on url, so if you randomly mess up an unimportant part of the url, you can get around it. One advantage to this method is that you actually want the browser to cache some pages, but not others, and this is a more client-side way of determining if you want a fresh copy from the server or not.

Asp.net mvc Specified UserAgent no session Id

I have a problem with my project Asp.net mvc 1.0, with .net framework 2.0. My application is hosted on a IIS 7.5. My authentication form looks like this:
<authentication mode="Forms">
<forms protection="All" loginUrl="~/Account/LogOn" timeout="60" cookieless="UseUri" />
</authentication>
<httpRuntime executionTimeout="1000" maxRequestLength="600000" />
<sessionState mode="InProc" cookieless="UseUri" timeout="60">
</sessionState>
When a user connects to the webpage, he receives a session id which is stored in the URL. When I connect to my webpage with the default UserAgent (in every browser, Chrome/FF/IE) everything works fine. When I override the browser UserAgent and try to connect with the User agent XXXXXXXX.UP.BROWSER, I receive an infinite redirection loop to address
http://<IP>_redir=1
But when I connect to the default webpage IIS - the user agent doesn't matter and everything loads fine, so it must be a problem with the specified UserAgent and my Application. I tried to find any filters for that XXXXXXXX.UP.BROWSER UserAgent but there aren't any. When I studied application lifecycle I tried to find the differences between good connection and wrong connection and found that functions which are NOT executed are:
Application_AcquireRequestState
Application_PostAcquireRequestState
Application_PreRequestHandlerExecute
Application_PostRequestHandlerExecute
Application_ReleaseRequestState
Application_PostReleaseRequestState
Application_UpdateRequestCache
Application_PostUpdateRequestCache
and another clue I found is that there is no Session in "wrong" connection - Session object is null.
To sum it up: The connection to my application web page with a specified user agent makes an infinite redirection loop, probably because of the lack of the session ID. What could be the problem ?
EDIT: I discovered that User Agent that contains "UP.Browser" is related to mobile. When I changed cookieless to "UseCookies" everything works. Why option "UseUri" doesn't work for mobiles?
EDIT2 : /admin -> my webpage hosted on specified IP address.
Good connection :
Wrong connection:
Sorry, I don't know how to make these images bigger.
http://msdn.microsoft.com/en-us/library/aa479315.aspx
So you're putting two different values into the URI, one for session and one for forms, which would probably create a lengthy URI:
"The principal limitation of this feature is the limited amount of data that can be stored in the URL. This feature is not targeted at common browsers such as IE, since these do support cookies and do not require this feature. The browsers that do not support cookies are the ones found on mobile devices (such as phones), and these browsers typically severely limit the size of the URL they support. So, be careful when you use this feature—try to make sure that the cookieless string generated by your application is small."
My guess is that the key to the infinite redirect loop is this functionality:
"// Step 5: We can't detect if cookies are supported or not. So, send a
// challenge to the client. We do this by sending a cookie, as
// well as setting a query string variable, and then doing a
// redirect back to this page. On the next request, if cookie
// comes back, then Step 3 will report that "cookies are
// supported". On the other hand, if the next request does not
// have any cookies, then Step 4 will report "cookies not
// supported".
SetAutoDetectionCookie();
Redirect(ThisPage + Our_auto_detect_challenge_variable);"
Unfortunately, this sounds like a bit of an architecture rethink, as it's probably going to now matter what the full path to your site is and you may have to drop automatic handling of forms authentication.
As you said the issue is for mobile browsers, I think this issue is limited to the devices(MOBILE) where the cookies are not supported and the Size of the URL increases and mobile browser severely limit that size, as mentioned in the MSDN reference article above.
My solution was to change User Agent containing "UP.Browser" to something else using rewrite rule. Everything works fine ;)
Edit: I found another clue.
In mobile browser - these with user agents containing "UP.Browser", it was necessary to add slash at the of the address.
In conclusion:
Everything works fine for user agents not related with "UP.Browser".
User agents containing "UP.Browser" needed address like:
http://addr/controller/
I don't know why it is necessary. Any ideas?

Asp.net ajax - losing session variables - Internet Explorer 8 and prior versions

I have been working on a legacy project (although C#) and trying to solve a session problem that have been encovered for years. It hapens on IE8 and prior versions. On IE9, Google Chrome, Firefox and Safari works fine.
In other words, we have a management software that works fine on all browsers. But there is a specific page that makes tons of Ajax requests, and in some point it loses the session data.
I have checked for cookie problems with Fiddle but they are always sent and the same.
These clues make us think that the problem is within the application. But if we remember the problem occurs just in IE8 and prior versions we think the issue is probably in the browsers.
We also use a legacy Ajax library. And the problem mustn't be there as many of our aplications
use it and they doesn't have the same problem.
We are using IIS7 with State Server
I'm almost out of ideas. I hope you have some.
I got it!
Using Fiddler, I saw a very suspect request for "/". There was something requesting for the site base URL. And I remembered that the default page of this particular web application kills the session data, in other words calling the login page also means to log the user off.
After some hours of debugging and sniffing I found what was making such request.
There is a javascript function that creates some image tags. Some times those tag were created with an empty address, in other words the src property of the img tag was a string with 0 legth.
It must be an IE8 and older versions bug, as they request the website root instead of not requesting anything. Maybe it's not a bug, but this behavior is certainly unexpected.
Phew! I still can't believe I found it.
Losing session state can be result of the application error. But if you claim that this happens only on IE8 and older versions, this could not be the case...
So I would suggest you to use page ViewState instead of session state. Let me know if did the trick for you?
Here is sample how to create propety based on page viewstate, just make sure you have enabled viewstate on page level:
public string MyProperty
{
get
{
return ViewState["MyProperty"] as string;
}
set
{
ViewState["MyProperty"] = value;
}
}

Call a method on browser closing

I am facing an issue in my application when a user directly clicked on browser close [X] button. Browser can be IE, Chrome, Mozilla, Firefox and many more.
What I want to do:
1. as soon as user hits [X] button of browser, need to set their status as logged off in database for which we have a method in Login.aspx file which is within the master page.
2. We do not have any Logoff feature in the application
I will be thankful if anyone suggests a solution to call the method which sets the user status as logged off from master page.
Thanks in advance.
This is not possible due to the nature of http connections and the web in general. Simply have a timeout (eg. 10 minutes) after which a user gets logged out automatically.
Javascript has an onunload function, so you could do:
<body onUnload="doFunction()">
However this, and other methods are going to be unreliable (I'm not sure in which specific instances it is fired) as it would be a security concern allowing websites to have access to perform many functions on browser onunload.
The best solution would be to have cookies/sessions automatically time out, and also to educate users to logout if the system is sensitive.
If you are using jQuery you could work with
$(window).unload( function () {
$.ajax({ **your params** });
} );
But I have to agree with Tom Gullen here - your sessions should timeout eventually.

Categories