Page_Init vs. Page_Load to read session data - c#

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

Related

Session variables are not cleared when the page is refreshed

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.

When Using Server.Transfer is the entire Asp.Net life-cycle executed again?

I understand that Server.Transfer doesn't make a round trip back to the requesting client.
What I haven't been able to learn is if control is simply passed directly to the new request handler you're transferring to or if or if the entire request life-cycle is executed again.
I assume the entire life-cycle is executed again using the transfer URL but wanted to verify this was the case.
Here is what I found through experimentation.
When using Server.Transfer the entire request life cycle is not ran again.
If you write your own Module, hook it into the request life cycle, and call Server.Transfer from that module the rest of the request life cycle will be skipped and the page life cycle will begin immediately.
After completing the transfer page life cycle the request life cycle picks back up with its tear-down events. Note, the HtppContext in for the tear-down events will be the original one you transferred from. That is, the URL and QueryString values will be the same as the original request and not be the URL and QueryString values for the page you transferred to.
Server.Transfer does modify the HttpContext.Request object to contain the new URL and QueryString information during the page life cycle for the page you transferred to.
If you transfer to a resource that is not a page but is text based (e.g. something.xml) the content of that page will be returned exactly as is with its encoding set to text/html.
If you transfer to a resource that is not a page and is not text based (e.g. something.pdf) then an HttpException error will be thrown. This happens even if you have defined a custom Handler for this resource.
It's just passed along, with its state intact. The request lifecycle does not get run again, although the page lifecycle will run for the page you're transferring to.
http://msdn.microsoft.com/en-us/library/ms525800(v=vs.90).aspx
Server.Transfer acts as an efficient replacement for the Response.Redirect method. Response.Redirect specifies to the browser to request a different page. Because a redirect forces a new page request, the browser makes two requests to the Web server, so the Web server handles an extra request. IIS 5.0 introduced a new function, Server.Transfer, which transfers execution to a different ASP page on the server. This avoids the extra request, resulting in better overall system performance, as well as a better user experience.
This link is also helpful -
http://www.developer.com/net/asp/article.php/3299641/ServerTransfer-Vs-ResponseRedirect.htm

Avoid the http handler to kill the page life cycle

I’m building an asp.net web application; I’m using an http handler as a filter, because I want the user to be redirected to a certain page if a condition is true. Problem is if the condition is false the page doesn’t load because the http handlers kill the life cycle of the page itself…so, is there any way to avoid this and to load the page properly or am I supposed to use another object to filter?
A handler, as its name suggests, must completely handle the request. If you want every request to be examined and filtered, you want to use an HttpModule.
A good 'getting started' guide can be found here.

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