Session variables are not cleared when the page is refreshed - c#

I have declared session variables in my web application.When i close the web application through tab i.e when the tab of chrome is closed the session variables are not getting cleared.But when i close the entire window the session variables are getting cleared.
Is there any way wherein i can clear the session variables when the page is refreshed?

I think you shold allow the user to decide this, by calling Session.Abandon() from a Logout button/link. As a user, you may not want your session to expire just because you have closed the tab.
You can also use Session.Clear() to clear down session data, but this does not remove that session. If you want to clear data on page refresh, then you could call this in the Page_Load event. Note, Session.RemoveAll() will do the same thing.
Take a look at HttpSessionState for more information, explaining the above methods.
If you want the session to expire if no activity takes place, then take a look at the timeout option - this could be useful if the data is personal/sensitive and you would want the session to expire on a public machine, i.e. Internet Cafe.

Use Session.Clear() in Page_Load.Sessions will be cleared when refreshing page.

Session.Clear - Removes all keys and values from the session-state collection.
Session.Abandon - removes all the objects stored in a Session.
Use this in your Page_Load event

Try for Session.Abandon() method.
or
Session.Clear()
I think you need to use any of the method inside your Page_Load method.

Related

Session handling across multiple users and browsers

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.

Page_Init vs. Page_Load to read session data

This question might be ridiculous, sorry for that.
Which event is best for reading session data - Page_Load or Page_Init event?
Currently I am using Page_Load event for such tasks. But i have seen in an article to do in Page_Init event.
Thanks.
Update: http://csharpdotnetfreak.blogspot.com/2008/11/detecting-session-timeout-and-redirect.html
It doesn't matter, use the event where you need it. A Session variable is stored in server memory(by default), so it doesn't depend on the current page's lifecycle.
http://msdn.microsoft.com/en-us/library/ms178581.aspx
Session is attached with your request while http request passes through ASP.NET pipeline. So before the page processing begins, you have your session with you. Session is stored on the server and is attached to your user request with the help of session id cookie. This cookie identifies each unique request and attaches session data(Session Module does this work).
I think you are confused with ViewState, because ViewState is stored and read in page life cycle (LoadViewState and SaveViewState event)
Also the article that you have pointed is for detecting new sesssions and time outs. It makes sense to do all the checking in Page_Int, so that response is sent as early as possible
You can access the the session data at any any stage of the page lifecycle. It does not affect it in any way. There is nothing like the 'best' or the 'worst'.
Be more consistent. If your request need some kind of INFORMATION (no matter where you store it), then you should check the presence of INFORMATION before excuting the request.
If you store your information in sesssion than use:
Global.asax:Application_BeginRequest
this prevent you from copy-paste single requirement to multiple page.aspx

How to resend viewstate on Membership / Session timeout

Currently, when the using is logged in (using the built in forms authentication) and they let their session timeout, they loose all data when they submit a form. How do I make it so that the viewstate data is resubmitted AFTER logging back in? Example, if they were writing an email and it expires, how do I make it send after they relogin instead of loosing all their data? I don't want a solution that extends the session on these pages please.
viewstate will only work in postback-scenarios,you will lose it if you redirect.So i think you use session for your problem.
I agree with Shree..
You could use a timer of sorts and either do a save to the DB, Session, or Cookie w/ the temp date entered so far.
Also, what I have done on some applications, is before the session will time out give the user a warning popup to "Continue" the session. This takes a little more work..
If you want to preserve the state of the form along with all form data, you don't want automatic redirects to the login page, which means that you need some sort of an "in place" authentication. You may consider intercepting the postback, i.e. adding your own handler to the form submit event, and issuing an AJAX callback to check your session state. If the session is valid, just proceed with the postback, otherwise display a login page in a popup or a modal dialog. The user will be able to resubmit the form after logging in.
I think your problem is not on ViewState, simple solution is save the email and action into local storage[HTML5], when user re-logs on, check the previous action and email, then you can submit email automatically. All browsers except IE6/7 already support local storage now.

C#.net webform, avoid losing data from session timeout

I have a user complaining about frequent timeouts in my Intranet web page. While looking for a solution I found this post:
http://forums.asp.net/t/152925.aspx?PageIndex=1
Where a poster recommends intercepting the redirect to the login page, submit the data to the database, then either reauthorize the user (without their knowledge) or redirect to login page. My goal is to avoid the situation where a user enters data in a form, walks away, then comes back to submit it, only to be told they have to login again (which is fine, if the data remained and the user was sent right back to the original webform).
Does anyone know how I can accomplish this on specific pages in my app (not all of them)?
It's not necessarily trivial, but you can add an ajax component that makes occasional calls to a page to keep the session alive. This way you could lengthen the session for any particular page you need to without affecting the application as a whole.
EDIT
If you really want to let the session expire, but keep the form data, you can implement
protected void Application_PostAuthenticateRequest (object sender, EventArgs e)
event handler in your global.asax.cs file. This is called before the forms authentication redirect happens, and the form data is available to your application at this point, so you can persist it to whatever medium is necessary until your user is authenticated again. In addition, if you check the
((HttpApplication)sender).Request.Path
property it will tell you which page was requested.
Well, the easy way it to drastically lengthen the timeout specified in the web.config file.
I'm going to try using cookies to preserve the data. My plan is to update the user's cookie after each control is changed, then add logic to the page_load property of the page to populate the form data after the user is logged back in.

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.

Categories

Resources