Should Session be checked on Page Load in ASP.Net? - asp.net

Page Load, as a sentence of 2 words, means when the page is loaded, means, when all elements are loaded.
Let's say I have a page called Ask.aspx, and this page is only allowed to users who have signed in, so technically I would write something like this :
if(Session["id"]==null)
Response.Redirect("Login.aspx");
This mean, that I'm testing the Session AFTER the page loads, theoretically, I think it sounds wrong, now of course I won't notice it, it will be fast, I will try to access the page, then I'm redirected to Login.aspx, but... is it correct to test the Session on Page Load method?

The Page_Load is part of the page lifecycle. It is called when the Server loads the page, not when the Client loads the page...
So this is the correct place to check the Session Variable...
You're actually saying: Before I post the page back to the client, check if I have the ID property set for this session... If I don't - tell the client to redirect to the Login.aspx page...
This is the correct way of doing this...
I recommened you also read about Server.Transfer. The difference between it and Response.Redirect is that in Server.Transfer the server itself "redirects" to another page and outputs the result of the new page back to the client (without the client knowing about it).

If you are trying to limit access to specific pages, you would be better off using forms authentication.
http://support.microsoft.com/kb/301240
It is fairly easy to setup and it allows checking of credentials before the request is passed to the asp.net pipeline. In what you are doing, your page goes through the entire lifecycle (controls are rendred and bound to data, access to database, calls to web services etc.) before the request is rejected. Depending on your situation, this might be costly and will not scale well.
Edit: You can also hook in to the AcquireRequestState event in the global.asax. This will also spare the entire page life cycle.

Related

What is a valid use for Response.Redirect("SomeURL", false)?

In ASP.NET I frequently use Response.Redirect to redirect the end user to another page on my system. I always set the second parameter to true to immediately end the response.
For the life of me, I can't think of a reason why anybody would ever set that parameter to false. What's the point of continuing generating a page when the end user's browser is just going to be redirected to a different page immediately?
Response.Redirect does not mean that The Page-lifecycle has ended on the server, it just sends a header to the client.
Perhaps you want to redirect the user first and THEN save his large amount of uploaded data to the database?
HttpServerUtility.Transfer by the way does terminate the Page-lifecycle, but it does not send a header, it simply serves a different page.
Response.Redirect(..., true);
client will be sent the redirect for the new page, processing will stop as a thread abort will occur
Response.Redirect(..., false);
client will be sent the redirect for the new page, current page will be allowed to continue processing, perhaps some cleanup work to do or something else
client will never see the results from current page in either cases
Why not. May be you have some things to complete on this page before the processes of a page will be killed. Writing to file and then colsing it for example. Or making some changes in DB, with proper ending of connection.
Response.Rediect("any page like Default.aspx");
When the control reach on this statement our page will be jump to the page that is specified into the brackets. The page may be .aspx, .asp.htm etc...

Call and receive URL data in asp.net

In asp.net (or vb) I must to call a page that only autenticates a user, returning the user data if the logon succed. This way, I would like to implement the sequence:
A blank page (mine) request the autenticator page (3rd part) automatically on load;
The user logs in the autenticator page;
My page reads the autenticator page results and do the actions.
I'm a very begginer in asp.net, and I'm using vb.net in the environment for coding the page "onload" event. I'm trying to use the "redirect('url')" method to call the autenticator's page, but in this way, obviously, I can't receive the result. How can I implement this sequence?
Problem solved. I discovered that when I call the autenticator server I must to inform a parameter with the URL for autenticator's page redirecting to (my page, in this case). This way, the autenticator's page itself will request my page after user login, then I'll be able to get the URL parameters with the user data. Thanks.

asp.net way to last URL from codebehind

is there a way from a asp.net-page code behind with "Request.Redirect()" or another method to redirect to the last page (like Javascript history back)?
You can check the Request.UrlReferrer property, which will be set if the user has navigated to the given page from another one. This is nothing more than the HTTP Referrer header that a browser will set. This will be null if the user navigates to your page directly.
HTTP is stateless, so theres no way of being able to read the browsers history (on the server) in the same way that Javascript can (its client side).
However there are a couple of tricks you can use:
Javascript could write the URL into a textbox which gets submitted to the server
The last URL visited could be stored in session - which can be retreived on a later visit
If using the URL in session method, you'll probably want to code this into a HTTP handler (not module) and this will fire automatically on every request.
Obviously these will only work if the user has previously visited a page, and not directly.

Prevent multiple users on a page at a time

What whould be the best way to prevent multiple users on a page?
For example if a user is at the page "Home.aspx", no other users should be allowed to go there.
I'm using asp.net on the server and the js-frameword jQuery on the client side.
The easy part is only allowing one user to access a page. You can for example store a session id in an application variable to keep track of who's on the page.
The hard part is to know when the user leaves the page. The HTTP protocol only handles requests, so the server only knows when a user enters the page. There is no concept of "being on" a page in the protocol.
You can use the onunload event in client code to catch when a user goes somewhere else, however this will not always work. If the user loses the internet connection, there is no way to communicate back to the server that the user leaves the page. If the browser or computer crashes, there will naturally be no onunload event.
You can keep requesting data from the server, by for example reloading an image on the page. That way the server can know if the user is still on the page at certain intervals. However, if the user loses the internet connection, the server will think that the user has left, while the user thinks that he/she is still on the page.
Another problem is browser history and cache. A user might leave the page, then go back to the page again. You have to make sure that the page is not cached, or the browser will just use the cached page and the server has no idea that the user thinks that he/she is on the page again.
Agreed with Guffa, you cannot be sure that the browser is already on the page or not, you can only check if the browser is already connected to that page or not.
You can do a sort of "ping", but its more a trick than a 100% working solution and it requires javascript enabled.
I didn't do it but I should look at XMLHTTPRequest and onreadystatechange to handle this :
1) On page load, the browser (client) initiate a XMLHTTPRequest with the web site (server) then wait for callback with the onreadystatechange event.
2) The web site receive the request and "mark" the page as "in use" with the current DateTime.Now.
3) Then the web site sends the response.
4) The onreadystatechange event get the response and the event code re-request the server to re-initiate the 2 after 1 min.
5) If another client request the page, the server check the DateTime mark : if the mark is greater than 1min ago, it means the client didnt respond to the request and may not be on the page again.
Not sure why you would want to do this because it flies in the face of web usability. You could do a locking mechanism on each page in server side code (write user name, page and time to a DB), which is freed up when they go to another page. You would then check on a the page load event to find out if anyone currently has that page locked. However, and this is a big however - have you considered what happens if somebody just shuts their browser down or walks off and leaves it on a page. You would need to seriously consider a timeout to free up locks too. That would need to be a back ground service, either in global.asax as global code or a separate process.
Maybe use static variables to hold the ip of the first user to access the page and then check whether other requests come from the same ip, otherwise display a "no access" page.
make sure you use lock it:
Object thisLock = new Object();
lock (thisLock)
{
// access static variables
}
You should also use "Session_End" method in global.asax to remove the ip address in case the user leaves your website without pressing the logout button

Why we cant use Server.Transfer() to redirect on another server

I know that Server.Transfer() should be used to redirect to another ".aspx" page on the same server. But what is the reason behind why should I not use this method to redirect to aspx page on another server or html page?
Your answers are really appriciated.
Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.
But watch out: because the "transfer" process can work on only those sites running on the server, you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.
Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.
From : Server.Transfer vs. Response.Redirect
So, in brief: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables.
Response.Redirect is more user-friendly, as the site visitor can bookmark the page that they are redirected to.
Transferred pages appear to the client as a different url than they really are. This means that things like relative links / image paths may not work if you transfer to a page from a different directory.
Server.Transfer has an optional parameter to pass the form data to the new page.
Since the release version, this no longer works, because the Viewstate now has more security by default (The EnableViewStateMac defaults to true), so the new page isn’t able to access the form data. You can still access the values of the original page in the new page, by requesting the original handler:
The Server.Transfer() only works within one webapplication.
With Transfer, the "handling" of the request is internally (to the webserver/application) passed on to another page, so the Request object stays the same. This means that the processing needs to stay within the webapplication.
If you want to let processing continue on another webapplication, you will need a fresh Request there. This means that you will need have the browser issue an other request, so you need a Response.Redirect.
Server.Transfer can only happen for single HttpContext. Each virtual directory or app has its own HttpContext object and they know not that they co-exists! so you cannot do that.
Take a look at Server.Transfer Vs. Response.Redirect
Sessions is not shared among servers so that would be a big problem.

Resources