Stop redirect page on back button click - c#

I'm trying to remove history for a particular site. When I'm logout the page and then press back button, the page move in previous page but I want when any user logout and then press back button it will be on same page that is login page not go in previous page. I'm trying all method like session abandon, cache remove but my problem not solved. We can also use JavaScript.
protected void btnLogout_Click(object sender, EventArgs e)
{
HttpContext.Current.Cache.Remove("");
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
Response.Redirect("../Login.aspx");
}

You can try using javascript:
<script type="text/javascript">
//Logout clears all visited pages for Back Button
function noBack() { window.history.forward(); }
noBack();
window.onload = noBack;
window.onpageshow = function (evt) { if (evt.persisted) noBack(); }
window.onunload = function () { void (0); }
</script>

If page is served using cache then do the below things to set the proper http headers
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();

You've two options:
Prevent page from being cached
Prevent user from going back to previous page after he logs out using JavaScript.
I would suggest the first one but if it doesn't work for you, go for the second option as mentioned here

From what I see, it looks like you are handling people logged on by session variables. If that is the case, then in the master page or a base page couldn't you check to make sure that person is logged on by checking the presence of a certain session variable? If they are logged on, continue as normal, if not then you could redirect them back to the logon page (or default) to make them log on?

In the code behind add the below code
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string strDisAbleBackButton;
strDisAbleBackButton = "<script language=\"javascript\">\n";
strDisAbleBackButton += "window.history.forward(1);\n";
strDisAbleBackButton += "\n</script>";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "clientScript", strDisAbleBackButton);
}
protected void Page_Init(object Sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}
Hope the above code will work for you.

Use react and then, useEffect to have constant looping default such as /page=0 or /login added to the path say /accounts/login/login so when they click back it will just re-route to the same page as it can't go back, because its an infinite loop.

This question has been asked several times in stack overflow.A simple search would get you a solution.
After logout you have to disable back button.for that you have to use
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Removing cache itself will stop navigating backwards.

Related

How to change after postback URL in asp.net 4.5 web forms

Here a button that does a postback
<asp:LinkButton runat="server" ID="btnBestPrice" OnClick="btnSearchBestPrice_Click">Search Best Price</asp:LinkButton>
Assume that this button is clicked on page
http://localhost:47207/Default?ClusterId=131
Now after the postback is completed, the page is still
http://localhost:47207/Default?ClusterId=131
However, after the postback, i want to make URL to be
http://localhost:47207/Default
Is that possible?
If i make a redirect, the postback event would be loss. I still want to process the postback event perfectly fine. So if somehow i can set the postback url to be raw url of the page on the client side or?
asp.net 4.5 web forms c#
I assume your postback is displaying some information to user, but have to change the URL without interrupt the process.
First of all you have to understand that if you changed the URL in the server side, the browser will treat it as a new page and make a new request. Response.Redirect is basically telling the browser it is time to move onto another page. So you cannot change the URL while remaining in the same request. (while Server.Transfer is remaining at the same URL but different page which is not what you want)
So I have 2 solutions for you, the following one make sense to me but there is still redirecting the page:
protected void Page_Load(object sender, EventArgs e) {
if (Session["ClusterId"] != null) {
try {
int ClusterId = int.Parse(Session["ClusterId"]);
// Code here
} catch { }
Session.Remove("ClusterId");
return;
}
}
protected void btnSearchBestPrice_Click(object sender, EventArgs e) {
int ClusterId = int.Parse(Request["ClusterId"]);
Session.Add("ClusterId", ClusterId.ToString());
Response.Redirect("~/Default");
}
Here is another solution that does all the actions in your btnSearchBestPrice_Click event without Redirect and Session, and bind a JavaScript page ready event, call history.pushState and also wipe out the unnecessary parameters in the action attribute of your form element.

Forward button after login asp.net

I am developing a website where i have a Login page.Once the user is validated,he will be redirected to User's home Page. If the user clicks on browser's back button,he will be redirected to login page because of the browser cache.Now from Login page if he click on brower forward button,because of browser cache he is able to see his home page without his credentials validated in login page.How do i avoid this?
Avoid moving back to Login page using this script in your login page..
<script type = "text/javascript" >
function preventBack() { window.history.forward(); }
setTimeout("preventBack()", 0);
window.onunload = function () { null };
</script>
We can also achieve this by disabling browser caching in code behind write the following lines of code in Page_Init event or Page_Load event and don’t forgot to add namespace using System.Web; because HttpCacheability related to that namespace.
protected void Page_Init(object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}
Here this JavaScript functionality will work in all browsers and prevent users navigating back to previous page by hitting on browser back button check below piece of JavaScript code
<script type="text/javascript" language="javascript">
function DisableBackButton() {
window.history.forward()
}
DisableBackButton();
window.onload = DisableBackButton;
window.onpageshow = function(evt) { if (evt.persisted) DisableBackButton() }
window.onunload = function() { void (0) }
Have you tried to debug this scenario ?
If user navigates back to login, you can deal with that scenario in page/control page_load event.
Alternatively if you are using visual studio, it is coming with boilerplate asp.net web application templates along with membership-ready implementation.
#jameem, #nayeem
We can't disable browsers back/forward button for such scenario, web is all about letting users click/move anywhere on the page, it's all about how you design solution with care.
Javascript is a language of the DOM, we better utilize it to deal with this part only.

ASP.NET: How to handle all page redirection?

In an ASP.NET page, are there any practical ways to handle all of these following:
PostBack
Redirection when user click a link in the page
Redirection when user change url field in the browser
with just a single web control (or method)?
TQ
Postback can be handled on the Server Side
the two others - link click or url field are ought to be handled using Javascript only.
UPDATE:
You can use jQuery to show a "loading animation" as mentioned in the question
$(window).unload( function () { alert("Bye now!"); } );
This will issue an alert once the user tries to leave the page. you can change it so it will display an animating gif image.
This must be tested though. I think it's pointless; not too sure on how long the gif will be displayed until the browser starts to load up the new page.
EDIT:
As I mentioned in comments, you can issue a postback using javascript
so, according to my last edit
$(window).unload( function () { __doPostBack("leaving"); } );
will issue a postback to the server, and you can catch it by:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreLoad += (sender, args) =>
{
this.ClientScript.GetPostBackEventReference(this, "arg");
if (!IsPostBack) { return; }
string __targetaction = this.Request["__EVENTTARGET"];
string __args = this.Request["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(__args)) return;
if (__targetaction == "leaving")
{
doSomething();
}
};
}
then again, I'm not too sure this will be too helpful, since the user is leaving the page.
PostBack
In this Page.IsPostBack will be = true
Redirection when user click a link in the page
In this case you will get value in referrer. You can use Request.ServerVariables["http_referer"] OR Request.UrlReferrer
Redirection when user change url field in the browser
Else this is the 3rd case

Javascript getting ignored because of Response.Redirect()

I am currently working on asp.net using C# and I need to show a message box and confirm the input from user and redirect to another page, my code is something like this:
protected void Button1_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>");
sb.Append("if (confirm('YES OR NO?')){ /*some javascript code*/ }");
sb.Append("</script>");
Page.RegisterStartupScript("FocusScript", sb.ToString());
Response.Redirect("Default.aspx");
}
here the problem is directly getting redirected to next page without showing message box.
if i remove Response.Redirect("Default.aspx"); it shows message box successfully. I think the here may be is Response.Redirect() has higher precedence compared to javascript
I tried using
sb.Append("if (confirm('YES OR NO?')){ window.location.href = \"Default.aspx"; }\");
instead of using Response.Redirect() but page didn't got redirected, what should I do to resolve this problem?
Do you absolutely need to handle this on the server side? Indeed this is where quite a simple thing is getting confusing.
If you could, for instance, handle it with Javascript / jQuery, you could do something simple like:
$('#Button1').click(function(){
if (confirm("Yes or No?")){
window.location = "/default.aspx";
}
});
There is an option of using adding javascript in client click event
eg:-
<asp:button id="Button1" OnClientClick="javascript:return confirm('Are you sure?');" runat="server" onclick="Button1_Click" />
and then in the code side simple redirect the page.
Confirm is a JavaScript function and it executes on client side. After you register it, you immediately redirect to another page, and so the function is never executed.
add following code on Page_Load
Button1.Attributes.Add("onclick", "if(confirm('do you want to redirect?')){}else{return false}");
now ur button click will first trigger java confirmation modal box.
as for ur Button1 click
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
The idea is - your codebehind Button1_Click event will be triggered only after user confirms by clicking OK
I think it is better to add an attribute to the button at page load and leave the button_click function to just redirect. Something like this (Page Load):
button.attribute.add("onclick","Javascript:confirmFunction();")
in button click just have this:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
finally in JS have this:
<script>
function confirmFunction()
{
if(Confirm("Yes OR NO")
//Add your JS Code
return true; //will pass onto server
else
//Add your JS Code
return false; //will not go to server
}
</script>
HTH

Logout or signout problem in asp.net c# using Master page and windows authentication

I am new in asp.net, My problem is facing logout problem in myappication using master page and window authentication. After i signout from my application if i use browser back button it again goes back to signed page after that i click any control then only it is goes back to the logout stage but i want to dont show the logged page unnessarily.
i am using href,document.location.replace(page),response.write("mypage.aspx") these technique for naviagation purpose and i am using session in all pages.
Note: I am using login and logout in master page top itself...so if i check the session for null redirect to home page which is also a content page then i am not getting the home page it self to login because infinite looping occurs...
when i am searching i got some coding to clear the cache but i a am facing problem that is after i logged and navigate to some of pages then i click browser backbutton without signout it is showing page is expired Click refresh to get the data back....
Finally, I need solution like google signout i.e: after signout from google page then if we use back it shows only the home page. and please tell which event is fired while clicking the browser backbutton if yes how to validate session and redirect to logout page.
Please help me i am facing these problem in one-week....
Thanks in advance to everyone..
Easiest way to resolve this problem is to disable the cache of the page.
This should help you out.
Login Page
protected void Page_Load(object sender, EventArgs e)
{
Session["imp"] = "0";
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session["imp"] = "1";
Response.Redirect("AdminHome.aspx");
}
Log Out Page
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
if (Session["imp"].ToString() == "1")
{ }
else
{
Response.Redirect("HomePage.aspx");
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session["imp"] = "0";
Session.Abandon();
Response.Clear();
Response.Redirect("HomePage.aspx");
}
You could consider in the Masterpage Page_Load to check for login credentials (however they are implemented in your solution) and if they are not present, to Response.Redirect() to the login or home page.
Edit: I'm not sure whether the OnLoad event is raised when using the back button. This approach may not work.

Categories

Resources