Session handling across multiple users and browsers - c#

I have to implement session handling across multiple users, and multiple browsers. Each user has a unique token which I save in HttpContext.Current.Session variable inside the Session__Start() in Global.asax.cs method. It works perfectly fine for a single session. However, when I fire the request from two browsers, then while browsing through various pages, sometimes the method Session_Start() automatically gets called for the second session and it resets the session variable, resulting in a null value.
How should I handle this scenario?
Edit 1:
What are the scenarios where the session may time out? Eg: switching between HTTPGet/HttpPost, or making Ajax calls?
I also read this link:
Does Session timeout reset on every request
Is this something which I should be keeping in mind? My code has 2 GET and 1 POST request, and the session variable becomes NULL in the POST method for the second browser session.

I figured out the reason. The sessionState mode in web.config file was set to "InProc", whereas it should be set as "StateServer". When I made the necessary change, then it worked like a charm.
ASP.net state service should also be started from services.msc for this to work.

Related

When do session variables go away?

I have a single-page, .NET 4.7.1 MVC application. My Page_Load() for Default.aspx.cs sets session variables and, when my breakpoint at the last line of Page_Load() is hit, the session object is stored correctly. However, when I click a link and hit my breakpoint on the first line of Page_Load() for the second call, HttpContext.Current.Session has no session variables set. Also, HttpContext.Current.Session.SessionID changes after the first call and then remains the same. Subsequent calls work correctly but the first one after an app pool recycle is always empty.
I have no httpCookies entry in the web.config and I'm always accessing via HTTPS. The app is running in an azure app service and I'm using OpenID Connect for authentication. Under what circumstances are variables removed from HttpContext.Current.Session before timing out?
UPDATE: I've added some diagnostic logging and sometimes SessionID changes without dropping the actual session data. I don't know how this can be but thought I'd record it. Also, it appears that my logging of the session ID has fixed the problem. I've seen others mention that the session is not preserved until it's been accessed (which is happening) but (without having searched exhaustively) I suspect all the session reading and writing in the first call is taking place in other assemblies and therefore perhaps not being 'counted' as reason to preserve the session? This seems very hokey but is my only guess for now. I'm still confused why it would have started breaking now.

Session variable gets cleared without any apparent reason

I have this piece of code:
var thisUser = Session["user"];
if (thisUser == null)
{
LogFile.Log("Logging out");
Response.Write("xp");
}
I am trying to track down why sometimes when I play with the system for a few minutes and suddenly the user session variable gets null.
It happens randomly in different scenarios.
I do not set the Session["user"] to null at any point.
Session timeout is set to 20 minutes.
I do not call Session.Clear() at any point.
Any ideas\thoughts\things I should look at as to why is it may happening?
I am using Firefox if that to any help.
The system is built with asp.net.
For more info please ask.
are you calling the same host? if the base URL is different the server will treat this as different users. for example:
http://localhost/path/to/resource and http://localhost:80/path/to/resource
both point to the same resource, but the requests are different and the session cookie will be different, or not present.
An easy way to test this is to launch your browser's developer toolbar and monitor the network traffic. compare the URLs to make sure they are the same base path and the same session cookie is passed in the request.
First of all this looks like C# and ASP.NET, not classic ASP. Now if you never clear the session yourself and the server (or the app pool) is never restarted, then the only way to lose the session is to clear the browser's cookies.
Editing the web.config will recycle the app pool, which clears the session info.

ASPX Losing Session when switching from HttpMethod POST TO Get

Recently I have been asked by a client to log into a legacy site using POST and not GET (from a 3rd party site), All of the needed variables are now sent within a post instead of a query string.
The problem is that upon receiving all of variables they are stored into Session and then redirected to the correct page within the application (from the logo-in Page).
While this works perfectly while calling the page using GET, a POST call will lose all of the Session variables after
Response.Redirect(#"~/SOMEPAGE.aspx",false);
Another thing that is odd is that the Session ID will remain the same but all values will be gone.
When Using Server.Transfer the session is intact but will be lost once the Response.Redirect is used. (there is no option to change all of the code.)
Does any one know of a way to resolve this or some sort of a work around that might be used.
Thanks!!!
There are a few reasons this could happen.
You are using Session.Abandon() in your code
You are switching between a secure (https://) and insecure (http://) URL
You have some code in your global.asax that is manipulating Session, or the .Secure or .Path properties of your Response.Cookie
edit http://forums.asp.net/t/1670844.aspx

How do you programmatically end a session in asp.net when Session.Abandon() doesn't work?

Session.Abandon() doesn't seem to do anything. You would expect the Session_end event to fire when Session.Abandon() is called.
This is most likely because your SessionMode is not InProc (the only one that can detect when a session ends).
Quoted from MSDN:
Session Events
ASP.NET provides two events that help
you manage user sessions. The
Session_OnStart event is raised when a
new session starts, and the
Session_OnEnd event is raised when a
session is abandoned or expires.
Session events are specified in the
Global.asax file for an ASP.NET
application.
The Session_OnEnd event is not
supported if the session Mode property
is set to a value other than InProc,
which is the default mode.
Session.Abandon() is the way to end a session. What is the problem you are encountering?
If its Back button related, that is a completely different issue ( page doesn't postback on Back, instead it runs one from clientside cache so no server side methods will execute).
Additionally, Session_End is problematic. It will only fire on Session.Abandon() when using InProc sessions, so if you are using a different Session mode, it cannot be relied on. Otherwise, Session_End will fire when SessionTimeout is reached ( default is 20 minutes I believe, configured in Web.Config ).
Have you tried using the following?
System.Web.Security.FormsAuthentication.SignOut();
This will clear cookies used for form authentication, although may not be what you're looking for.
You may need to use this in addtion to Session.Abandon()
If sessions appear to persist you might try (in web.config):
<sessionState regenerateExpiredSessionId="true">
It depends, if you have your application at 2 servers: 1 WebApplication that has its own session, and the second WS or WCF application that also has its own session, how it was in an application on which I was working once. Than if you have this case, the session must be ended at second point, and the first is ended the timeout appears. At least you'll have to use a token and to keep the list of tokens, of active sessions. May be it is your case. good luck. PS. To kill the session manage it in the second server.

IIS HttpModule unable to set Session

I am trying to set Session values using a IHttpModule. I have set the HttpModule to be used for all requests, not just managed/ASPX pages.
I found however, that when a request for a non-ASP.NET page came in (such as gif) the Session member of the HttpApplication would throw an exception or be null.
I found the following SO post for the reason behind this: link
When I am swapping out the HttpHandler with one that implements IRequiresSessionState the Session member is available in the HttpModule, and a Set-Cookie is sent back to the browser, but later when I try to read the contents of the session in a normal ASPX page none of the values I set are there. When debugging I can see that the SessionID is the same in both the HttpModule and normal ASPX page.
Do I need to do anything to force the session to be saved? I am assuming that while swapping in the fake HttpHandler initialises the Session, having to put the original which doesn't implement IRequiresSessionState back in causes the session to not be saved at the end of the request.
I just worked it out, I had to move the re-mapping of the original HttpHandler from PostAcquireRequestState to PreRequestHandlerExecute.

Categories

Resources