Request.Form[“__EVENTTARGET"] value not clearing - asp.net

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?

Related

Display message to user when forms authentication session expires

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.

Session timeout and AJAX in ASP.NET

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.

Redirect to webapp default document when another page is specified?

IIS6, ASP.NET 2.0, No Forms Authentication
I'm calling Response.Redirect("~/foo.aspx"), but the default document ("Default.aspx") for my site is appearing. To make matters worse, it only happens intermittently. Sometimes the redirect displays the right page.
I've checked session state, and I don't see any values in the web.config (that is, I'm assuming I'm using the 20-minute defaults).
I wish I had more relevant information to share (I'll do my best to answer any questions).
Any ideas? Why isn't it redirecting to the specified page?
EDIT: I've looked deeeeeper into the code and learned more details.
Ok. There's foo.aspx and foo2.aspx (and the default document, Default.aspx). All pages extend from BasePage, which extends Page.
BasePage has a property named ReturnPage:
protected string ReturnPage {
get {
if (Session["ReturnPage"] == null) {
Session["ReturnPage"] = "";
}
return Session["ReturnPage"].ToString();
}
set { Session["ReturnPage"] = value; }
}
Users click on a LinkButton on foo.aspx, and the click event handler ends with two lines of code:
ReturnPage = ResolveUrl("~/foo.aspx");
Response.Redirect(ResolveUrl("~/foo2.aspx"));
The Page_Load of foo2.aspx has problems, and its error handling calls Response.Redirect(ReturnPage).
When I view the response headers of foo2.aspx, the 302 location is string.Empty (that is, there isn't one). That same response header has the same ASP.NET Session ID as the response of foo.aspx.
And remember -- this is intermittent. Sometimes, you can click on that LinkButton and go effortlessly to foo2.aspx, no problem. You can process the click with the exact same data once, and it will fail. You'll navigate from the default document (Default.aspx, where you were sent by the "bug") back to foo.aspx, click again with the same data (the same row in the grid/table -- the same LinkButton, essentially), and you'll be redirected to foo2.aspx without issue.
Placing a value in the session immediately before a Response.Redirect() is risky.
Changing foo.aspx's Response.Redirect() to the following might retain the session value more reliably:
Response.Redirect("~/foo2.aspx", false);
UPDATE: This ended up being fixed only by moving our session state into SQL Server. See related question: Why/when are session writes vulnerable to thread termination?
When you say:
Sometimes the redirect displays the right page.
Does it just happen, and you are not sure if there are certain pages that are affected by the problem? If this is the case, then you probably have a addressing problem. You can use either a relative path or an absolute path rather than an Application-relative path. I would also guess that you are trying to either direct to a page from a subdirectory on your site or to a subdirectory on your site. If you choose to stick with the Application-relative path make sure that are taking the subdirectory into account. (ex: ~/FooPages/Foo.aspx)
Here is a good reference page I just found:
http://nathanaeljones.com/129/types-of-asp-net-paths/
I'm a little confused here. What exactly are you trying to accomplish? You're getting the default document exactly because the 302 is blank. Your "inconsistent" behavior is almost certainly due to the way you are saving data in the Session.
The real issue here is why you're redirecting when foo2.aspx "has problems". What's the problem here? Why redirect? If you really need to redirect, why is the redirect target changed? Make it a static error reporting page and you'll be fine.
Once you redirect and get a new instance of the BasePage from foo2.aspx, won't that ReturnPage property be null again? Then once your page load errors out and tries to redirect it will be accessing a null string. Maybe try throwing that property in the Session
Session.Add("ReturnPage","~/foo.aspx")
instead of
ReturnPage = ResolveUrl("~/foo.aspx");
Ofcourse you would have to modify that error handling in the page load to grab it out of session rather than the property and you may have to rethink how the whole redirect is working in your system if this turns out to be the issue.
EDIT:
To test this idea about the property not getting set, or getting set correctly....(just to test I am not suggesting you should hard code the path in there), change your getter to the example below, then check to see if it works. Hope this helps, I am curious to find out what the problem is if this is not the issue.
get {
if (Session["ReturnPage"] == null) {
Session["ReturnPage"] = "~/foo.aspx";
}
return Session["ReturnPage"].ToString();
}

Flex:Browser Refresh Issue

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.

ASP.NET passing values between redirect & postback

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

Resources