SessionID changing at every page call - c#

I'm accessing the SessionID using this code in my class:
HttpContext.Current.Session.SessionID;
however I find that SessionID changes at every page postback, this happens in a short time, so the current session should not expire already. I supposed that the SessionID to remain the same for the whole time until expired.

When using cookie-based session state, ASP.NET does not allocate
storage for session data until the Session object is used. As a
result, a new session ID is generated for each page request until the
session object is accessed. If your application requires a static
session ID for the entire session, you can either implement the
Session_Start method in the application's Global.asax file and store
data in the Session object to fix the session ID, or you can use code
in another part of your application to explicitly store data in the
Session object.
like
protected void Session_Start(Object sender, EventArgs e)
{
Session["init"] = 0;
}

You should Use the Session_Start method in the application Global.asax file. Below Link may help you
ASP.NET: Session.SessionID changes between requests

Related

Redirect from Global.asax

HttpContext.Current.Response.Redirect("~/default.aspx");
When i use this code in session_end in global.asax
error to me:
Object reference not set to an instance of an object.
why?!
Session_end is not an event that gets called by the user of your application, it's something that gets called by the server when a session times out. So when you try to access HttpContext, it is null because there is no HttpContext to access (no user who is currently performing some kind of interaction with your site).
Your attempt to redirect a non-existing HttpContext will always fail no matter what you do.
When the event SessionEnd is raised the Request and then the Response are null.
HttpContext.Current.Response //this is null
This is by design: Session ends not during a request but when the session timeout
It usually (default config) happens 20 minutes after the last request.
Since there is no request there is also no response.
You need to understand better how Asp.net Session State works
Anyway if you want to redirect the user to a page if the Session is expired you can check for one of your variables stored on session:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["YOUR_VAR_NAME"]==null)
{
Response.Redirect("~/default.aspx");
}
}
Session_End is fired internally by the server, based on an internal timer. Thus, there is no HttpRequest associted when that happens. That is why Response.Redirect or Server.Transferdoes not make sense and will not work.
I hope the above information will be helpful

ASP.NET MVC4 - Session_End - How can I get the currently logged on user's name in Session_End of Global.asax?

My issue is that once Session_End executes in my Global.asax, the HttpContext.Current object no longer exists- probably as expected, I would imagine. So, what I'm trying to do is once the session ends, update my Logins table for the user currently logged in and set their LoggedIn status to False. Here's my Session_End:
protected void Session_End(object sender, EventArgs e)
{
Helpers.OperationContext.UpdateIndividualLogin();
}
As you can probably guess, I can try to pass in:
System.Web.HttpContext.Current.User.Identity.Name
But this object no longer exists because I can only imagine that it's already been disposed of. So, is there any way I can grab the currently (or previously current) user's name?
You can do this by storing the information you want (in this case the user name) in Session. You can store it when the user is authenticated.

Prolonging asp.net session enddate?

How is asp.net Session prolonging, does every request prolongs the end date of Session, and is it enough to call void() by ajax to extent Session end date by another period of time(default 20 min or so...)
public void ResetSessionTime()
{
}
or do i have to invoke session in some way:
public void ResetSessionTime()
{
User currentUser = HttpContext.Current.Session[userSessionKey] as User;
}
how does simple request extend session end date?
This question claims every post-back prolongs session...
This MSDN about Session State Providers :
"Each session created by ASP.NET has a timeout value (by default, 20
minutes) associated with it. If no accesses to the session occur
within the session timeout, the session is deemed to be expired, and
it is no longer valid."
How does request access the session exactly?
THIS QUESTION: Keeping session alive C# does not answer how session end date is prolonged by request, only a opinion on how to keep session alive from client side
EDIT:
According to this article, method needs to be extended from IHttpHandler, in order to access current session...
public class KeepSessionAlive : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Session["KeepSessionAlive"] = DateTime.Now;
}
}
Every time you make a request, the session timeout is reset. A request can be a page load or something like an ASYNC call.
Take a look at this question for an example of how to keep the session alive by periodically making AJAX calls to the server. (Keeping ASP.NET Session Open / Alive)

ASP.NET sessionID will not update

I click on refresh button which should restart session:
protected void btnRefresh_Click(object sender, EventArgs e)
{
HttpContext.Current.Session.Abandon();
HttpCookie mycookie = new HttpCookie("ASP.NET_SessionId");
mycookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(mycookie);
LblSessionID.Text = HttpContext.Current.Session.SessionID+
" test btnRefresh_Click";
LblIsNewSession.Text = Session.IsNewSession.ToString();
}
But when the button is clicked, the SessionID value in LblSessionID still displays the old value but another label LblIsNewSession will show it as true for IsNewSession. The LblSessionID will then reflect the actual SessionID value when I use asp.net control (like dropdown) that has autopostback="true" and from there SessionID sticks around.
I do use global.asax
Any idea why LblSessionID isn't behaving as it should and is waiting for next postback to start reflecting actual value?
When I launch the web application, the problem is the same - LblSessionID show different value and then change after first postback and stays the same from there.
That's the way it works - If you Abandon the session it won't reflect that until the next Request. It makes sense if you think about it...
Say you have a user that accesses your site and gets a Session ID of 123 (not reflective of an actual value, I know). When you click your button to get a new Session ID, the user's request is from the old Session, and that is the value that is reflected during that Request. Once the session is reset (or abandoned or whatever), the user gets a new Session ID of 321 and subsequent Request's will then reflect that new session ID.
SessionId is not reliable unless you actually store something (anything) in the session.
try
Session.RemoveAll();
Session.Clear();
It is not your code, it is a documented behavior:
"The Abandon method sets a flag in the session state object that indicates that the session state should be abandoned. The flag is examined at the end of the page request. Therefore, the user can still use session objects after you call the Abandon method. As soon as the page processing is completed, the session is removed."
(source: http://support.microsoft.com/kb/899918)
The Abandon() method flags the session collection for clearing at the end of the request, it does not actually clear it immediately.
You can either call the RemoveAll() or Clear() methods for instant deletion of the objects, or issue a Response.Redirect call to the page itself and re-test for the existence of the data.

Using Cache ASP.NET

How can I use Cache in ASP.NET which is accessible by all users not just a specific user context while having a specific key of this cache removed automatically when a user closes the browser window or expires (like a session object) ?
Cache is accessible to all users, you can set it to expire after a period of time:
Cache.Insert("key", myTimeSensitiveData, null,
DateTime.Now.AddMinutes(1), TimeSpan.Zero);
You may remove the cache entry whenever a session expires by implementing the global.asax's session end event
void Session_End(Object sender, EventArgs E)
{
Cache.Remove("MyData1");
}
See this for more details on Cache
Edited:
Regarding your question on how to react when the user closes its browser, I think that this is not straightforward. You could try javascript on the client side to handle the "unload" event but this is not reliable since the browser/client may just crash. In my opinion the "heartbeat" approach would work but it requires additional effort. See this question for more info.
You'll have to use the Session_OnEnd() event to remove the item from the cache. However, this event will not fire if the user just closes the browser. The event will only fire on the session timeout. You should probably add a check to see if the item has already been removed:
public void Session_OnEnd()
{
// You need some identifier unique to the user's session
if (Cache["userID"] != null)
Cache.Remove("userID");
}
Also, if you want the item in the cache to stay active for the duration of the user's session, you'll need to use a sliding expiration on the item and refresh it with each request. I do this in the OnActionExecuted (ASP.NET MVC only).
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Put object back in cache in part to update any changes
// but also to update the sliding expiration
filterContext.HttpContext.Cache.Insert("userID", myObject, null, Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(20), CacheItemPriority.Normal, null);
base.OnActionExecuted(filterContext);
}

Categories