I have a button that executes a script using AJAX.
Normally when a session is still active the script will return some data that will be placed inside the parent page.
If the session expired the AJAX will return the login screen which gets placed inside the parent page which looks really odd.
How would I be able to detect a session timeout and do a postback on the parent page?
Since you are unlikely to be calling a full page, and you login page is likely to be a full page, you could just do the following.
if (xmlhttp.responseText.indexOf("DOCTYPE") != -1) {
window.location.href = window.location.href;
}
When you make your call, first check to see if one of your session parameters is Nothing/null. If it is null, then your session has likely timed out. If you don't have any session variables that you explicitly set, you can set one when the user logs in.
What do you mean by 'if the session expired the AJAX will return the login screen'? You are in control of what is returned, so instead of returning the login screen return some sort of error code, or better throw an exception which you can catch as an error on the client.
Related
When I try to log off the system, my login page is loaded. After that press the browser back button and it shows web page has expired and when I refresh the page, the database call is again made since the value in Request. Form[“__EVENTTARGET”] attribute and textbox values are retaining its previous values and the function for logging in is again executed.
Please suggest a way to solve this issue.
Ex : Server side code is given below:
if (IsPostBack)
{
string parameter = Request.Form["_EVENTTARGET"];
string argument = Request.Form["_EVENTARGUMENT"];
if (parameter == "LOGIN")
{
ValidateLoginDetails();
}
}
After log off, When I press the browser back button, browser shows web page has expired. Then I refreshed the page and I am getting the values of the string parameter. What can be the reason and how can I solve this issue.
Sounds like you haven't logged the user out correctly - you shouldn't be able to hit server-side code on a page that's configured to be authenticated until authentication has happened.
Another option is that there's a problem with the authentication configuration - have you checked that User.Identity.Name returns the value you expect?
This seems simple and I remember doing it a couple of years ago.
I simply want to display a message on the login page when the user is automatically redirected there after requesting a page that they were logged in for but their session has now expired. So essentially if the user was working but stepped away for a lunch break without logging out I want the system to tell them why they were sent back to the login page.
Something like "You have been idle for too long so you must log back in".
This has to be easy I am just running into a wall here. I thought about getting the original ticket and reading the expiration date but I'm a little lost.
Any ideas?
Brent
Try this JavaScript on for size:
Make sure that a property called LoginPageUrl exists on the code behind. Great for Master pages.
If you want to register the script from code-behind, you could even pull the session timeout from the application and inject it so that you still only have one place (web.config) to update it.
To display a message to the user after redirecting them to the login page (.NET will take care of expiring the cookie), send a query string parameter that the login page looks for and shows a message indicating that the user was logged out due to inactivity.
<head>
...
</head>
<body onload="logoutOnExpire();" >
<script type="text/javascript">
// ACTIVITIES TO RUN FOR THE PAGE
function logoutOnExpire() {
clearTimeout(logoutTimeout);
logoutTimeout =
setTimeout('location.href = '<%= LoginPageUrl %>';', 1200000);
// 20 minutes
}
</script>
<form id="form" runat="server">
...
</form>
</body>
</html>
You can check the session in the inner page and if session does not exist,Redirect to the login page with some value in querystring to understand from which page this call came.When user logged in back,You can use the querystring value to determine which page to be displayed back.
MyPage.aspx.cs,In Page load you can check,
if(Session["user"]==null)
{
Response.Redirect("Login.aspx?from=mypage");
}
else
{
// Do the other stuff for the loged in user
}
And In Login.aspx.cs,In the code where you check your login details from the form
string userName=txtUserName.Text;
string password=txtPass.Text;
if(IsValidLogin(userName,password)
{
string toUrl="defaul.aspx";
if(Request.QueryString["from"]!=null)
{
string fromPage=Request.QueryString["from"];
if(fromPage=="mypage")
{
toUrl="mypage.aspx";
}
else if(fromPage=="review")
{
toUrl="review.aspx";
}
}
Response.Redirect(toUrl);
}
If what you want is to send the user to a page other than the login page when they cause a server postback after their session expires, use the following code at the top of the Page_Load event (this may not work if .NET executes it's redirect first).
if(!Context.User.Identity.IsAuthenticated)
{
Response.Redirect("~/OtherPage.aspx", false);
}
If you create a base page in your website that all pages inherit from, add it to that page's Page_Load.
If you are redirected to the default login page, after an attempt to use a page after your session has been timed out, is not the redirecturl param set to the page you were trying to access.
So you could infer that if that is set they were previously on a page and then present your message about being logged out due to going for lunch., etc.
I was working with my application which shows login first time and goes to the second screen after successful validation. But there is a problem occurs when browser get refresh by F5 or browser button the application gets reloaded and shows the very first screen i.e. the Login screen.
How to avoid this, I mean irrespective of browser reloading the current screen/component should remain intact (it should not start with the beginning).
As an example I have a link from where I took this example & uses in my code:
http://www.vipercreations.com/media/tutorials/login_system_with_flex_and_php/
credentials: user: test and pass: test
Here, once u logged in and press F5 you will back to the Ist screen rather than staying at the same screen.
Thanks,Shuo
If your login creates something like a session you can pass that same session object to the application via FlashVars.
When your application is starting, test if a session is already existing. If existing, validate it against the server. If successful: you are logged in, so skip the login screen. Otherwise: show login screen.
Besides: This is not a refresh issue but boils down to session management. Instead of hitting the refresh button I could also open the same website again and would have to login which seems akward.
Ofcourse it will reload, it is not the flash who is reloaded.. its the whole web page. or HTML file.
I have this code to disable F5 or refresh
<script>
window.history.forward(1);
document.attachEvent("onkeydown", my_onkeydown_handler);
function my_onkeydown_handler()
{
switch (event.keyCode)
{
case 116 : // 'F5'
event.returnValue = false;
event.keyCode = 0;
window.status = "We have disabled F5";
break;
}
}
</script>
You could store the sessionID in a cookie via ExternalInterface or in a shared object. This way you can even add a expiration date that of course should be in sync with the serverside expiration of the session.
Additionally you can use the HistoryManager or the BrowserManager to encode states of the app in the URL. If you design the states carefully, hitting F5 (or accessing the page via bookmarks) will direct the browser to the last state instead of the beginning. Just remember to verify the session.
I am using VS 2005, C# 2, ASP.Net 2.0
I am unable to find out how to track that user pressed F5/Ctrl+F5/ Open a new Window(Ctrl + N) in ASP.Net.
I know that there is a Page.IsPostBack property, which tells that a page is loaded in response to an action taken by user.
I am just curious to know, that why isn't there a property as IsRefresh or Page.IsRefresh in ASP.Net, which will return true,
whenever user takes any of the above actions.
Is there a way to know this?
Actually my problem is that i have a DLL using which all of my aspx pages are inherited, I have to
insert some values in a table whenever the page is opened for the first time that's it, if user just opens the page or do not take any action,
an entry should be inserted into the database, but as far as I have tried, I controlled it anyhow using the Page.IsPostBack property, but I got stuck
in the refresh case, as it is inserting records unconditionally.
Similar to using a function in Global.asax (as others have suggested) you could use a session variable "flag". When the page first loads set a session variable and then just check against it in your page load function:
if (Session("visited") != "true"
//page has not been visited, log visit to DB
Just make sure you set the session flag sometime after the above check during the page load.
It won't be exact (sessions can timeout while a page is active, users can completely leave the site and come back in the same browser and the session stays alive, etc) but for your tracking it is much better than counting every page hit in the DB.
Perhaps you want the Session_Start method in the Global.asax file, which will be triggered once at the start of each user session?
In your Global.asax file, add or edit the method:
void Session_Start(object sender, EventArgs e)
{
}
why isn't there a property as IsRefresh or Page.IsRefresh in ASP.Net
Because ASP.NET cannot possibly know. The browser does not send any information that could allow it to determine whether the page is being requested due to a refresh or normal load. You will need to reconsider your requirements: what is the actual purpose of the database logging?
Session_Start method in Global.asax file is fired every time when a browser session is started. You can use this method to count number of unique users on your website.
Session_End method in Global.asax is fired when a session ends (explicitly or timedout). So you can decrement the count here.
Hope the above to example uses of these methods helps you understand how you can use them.
Because of the stateless nature of HTTP protocol there is no way to tell apart the initial load from the refresh
As has already been said. This isn't possible. A request issued due to a refresh is no different to a request issued the first time the page is loaded.
It sounds to me like you are trying to track page views somehow. This is certainly possible though it will require some work on your part. Your best bet is probably to log the URL of the page. You may also want to include the query string in order to differentiate between page loads for different pieces of data (if this happens in your application). You will also want to log the ID of the current user, and the ID of their session.
You can then make sure that you don't insert two page views for the same user for the same page in the same session, effectively filtering out any reloads of a page.
You do need to be aware that this isn't the same as detecting a refresh, what you are detecting is two page views in the same session, this could be a refresh, or it could be use of the back button, or just reloading from the address bar.
My suggestion would be to create a cookie on very first load, then on Page_Load check to see if the cookie exists. If it does, don't insert the record. You can use Session_End to destroy or create the cookie as someone suggested if that works with your application's architecture.
First of all, thanks for reading.
I will describe my situation as explicitly as I can.
I have a page where users can leave comments.
Here's the commenting flow
A-1. 'comment' button is clicked
A-2. a modal popup with a textbox is shown using ModalPopupExtender in ajaxtoolkit.
A-3. User types a comment in the textbox, and click "ok".
However, when user is not logged in, expected behavior changes.
B-1. 'comment' button is clicked
B-2. a Login modal-popup with id & pwd textbox is shown.
B-3. User types ID & pwd, and click ok.
B-4. Comment-modal-popup is shown
B-5. user types a comment and click ok.
I have a PROBLEM handing this case.
When B-3 occurs, page is posted back, i log the user in, update session object, and I Response.Rediect() the page to itself to display correct logged-in status (i have to..).
After redirect, in Page_Load(), I need to check some values to show Comment-Modal-Popup.
But I'm not sure how..
Here's what i considered
ViewState
i just can't use it since the page was redirected not posted back.
QueryString
I could have add "showCommentPopup=1" on URL when redirecting, but that will leave unwanted QueryString in URL. I don't want users to misuse it.
Session
I actually used Session object. Before redirection, I set Session[ "ShowCommentPopup" ] to true. In Page_Load() if it is set, i remove it and show the popup.
using Session like i did doesn't work correctly when user opens same page in multiple tabs.
user opens two tabs(in Firefox) with same URL
user follows steps from B-1 to B-3 in first tab.
before the page is redirected between B-3 and B-4, user refreshes second tab.
if the timing is right, comment-popup is shown in the second tab.
I expect to hear great insights from stackoverflow..
I haven't tried this but I think if you store your ShowCommentPopup flag in the HttpContext.Items collection instead of the session and then use Server.Transfer instead of Response.Redirect you should be able to achieve the desired results.
HttpContext.Items is a dictionary that can be used to store data whose lifetime is the lifetime of the request. This means a second request from a different tab or window will have a different HttpContext.Items dictionary.
Server.Transfer is somewhat like Response.Redirect in that it allows you to load a "different" URL instead of the original. However, while Reponse.Redirect initiates a new request, Server.Transfer transfers the existing request to the new page on the server.
A better explanation of the differences between Response.Redirect and Server.Transfer can be found here.
Example
bool showCommentPopup = false;
if (HttpContext.Current.Items["ShowCommentPopup"] != null)
{
showCommentPopup = (bool)HttpContext.Current.Items["ShowCommentPopup"];
}
//...
HttpContext.Current.Items["ShowCommentPopup"] = true;
You've clearly thought your solutions through! I'm guessing the problem with the Session was that they could comment on a different page than the one they logged into. You could get around this by storing the session var, not as a bool, but as the page to show it on:
var uniqueString = this.ToString() + uniquePageID;
if (Session["ShowCommentPage"].ToString() == uniqueString)
//show modal & remove session var
Now your program only "breaks" when the user visits the same object in two different windows, logs in on Window #1, and refreshes on Window #2. And it's not really breaking since they wind up commenting on the same object either way.
The reason I used uniquePageID, is cause I'm figuring you have a template page ("showObject.aspx") with arguments on which to show ("showObject.aspx?objectID=3"). In order to make sure the comment is left on the same ID, it needs to be present in uniqueString