ASP .net Always ask for log in on load - c#

I'm using ASP.net with C#, I have a form with master page and I need to show the log in everytime someone enters the page and logout when the information in the form is saved in database.
To save I use this code
<asp:Button ID="botonAcepto"
Text="Guardar"
runat="server"
ValidationGroup="validaARCO"
OnClick="btnUpload_Click" />
btnUpload_Click uses this code to redirect to logout
string scriptText = "alert('Datos guardados exitosamente.'); location.href='/folder/folder/logout.aspx';";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertMessage", scriptText, true);
But, when I try to force the log in page the button doesn't work.
I tried this 3 ways to force login on load. These page loads are not in the same document at the same time, they're the 3 set ups I tried on my Default.aspx.cs to force the login at load.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FormsAuthentication.SignOut();
Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
MaxUsersManager.RemoveSessionCacheItem(Context);
Session.Clear();
Session.Abandon();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
}
The 3 examples make the button useless, and the form goes to the login page and doesn't save the data.
How can I solve this? Is there any other way to always force the user to log in to enter the form and log out when the data is saved?
Thanks.

Related

asp.net Load Child page only from parent page

I have two pages MainPage.aspx and ChildPage.aspx. From main page when i click a button i redirect to ChildPage.
If i give the address of ChildPage directly on browser, i do not want to load it directly instead i want to redirect to MainPage.
the ChildPage must be loaded only if it is loaded from the MainPage.
How do I find from where the ChildPage.aspx is loaded. how to find the parent page of it or from where it is loaded.
can we try something in the below code
if (!IsPostBack)
{
if (finding_source)
{
Response.Redirect("MainPage.aspx");
}
}
You can use Request.UrlReferrer.AbsolutePath to see the previous page.
if (!IsPostBack)
{
if (Request.UrlReferrer != null && Request.UrlReferrer.AbsolutePath == "/MainPage")
{
//do what you want
}else{
Response.Redirect("~/MainPage.aspx");
}
}
TIP But be careful with using it with postbacks since it will change the value of Request.UrlReferrer to the current page during a postback.
Even though your question is not clear , here i am trying to give my solution.
MAINPAGE.ASPX BUtton Click
protected void lnkRegister_Click(object sender, EventArgs e)
{
Session["MainPage"] = "true";//Encrypt it if u wish
Response.Redirect("childpage.aspx");
}
CHILDPAGE.ASPX PAGE LOAD
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Session["MainPage"] as string) && Session["MainPage"].Tostring()=="true")
{
//proceed
}
else
{
Response.Redirect("mainpage.aspx");
}
}
GLOBAL.ASAX
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
Session.RemoveAll();
Session.Clear();
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}
it is little difficult to control browser shutdown or close...but you can workaround global asax file when your application shutsdown.

Navigate to a new page and display an alert box

I am developing an application by using ASP.Net WebForm. Once user click a button, application will navigate to a new page and prompt out a dialog box "Welcome to JackiesGame"
However, I able to navigate to new page but the alert dialog box does not display.
The following is my sample code
void cmdCancel_Click(object sender, EventArgs e)
{
HttpContext.Current.Response.Redirect(Globals.NavigateURL(TabId), true);
Page page2 = HttpContext.Current.CurrentHandler as Page;
ScriptManager.RegisterStartupScript(page2, page2.GetType(), "alertMessage", "alert('Insert Successfully')", true);
}
Add the following in page 2. On the page load it will register only for the first time the page loads the script.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
var reg = Request["Welcome"]
if(reg != null && reg.ToString() == "yes"){
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertMessage", "alert('Insert Successfully')", true);
}
}
}
All code after the redirect is getting ignored since it has to redirect to a new page. So the code never gets triggered.
EDIT
Added a example of how it can look further
void cmdCancel_Click(object sender, EventArgs e)
{
string myUrl = Globals.NavigateURL(TabId)+"?Welcome=yes";
HttpContext.Current.Response.Redirect(myUrl, true);
}

Detect Browser Refresh to Prevent a Method from Triggering in C# ASP.NET

So I have a Method that is setup to send out an email after the user reaches to this page. However, I want to prevent it from sending out again when the user accidentally refresh the page. Down below is my code:
protected void Page_Load(object sender, EventArgs e)
{
Session["ID"] = "50";
if (string.IsNullOrEmpty(Session["ID"] as string))
{
Response.Redirect("./default");
}
if (!Page.IsPostBack)
{
email();
}
}
I realized that refreshing the page isn't going to post back, it's more of a GET than a post.

How to prevent back button after LOGIN in asp.net?

I have 2 pages home.aspx and admin.aspx
After successfully logging into admin.aspx when i click back button of browser, it does redirect to home.aspx but that i don't want.
I am checking session variable persistence on home.aspx but for some reason its not working!!
Here's the code
home.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Session["aname"] != null)//should work as session will not be null!
{
Response.Redirect("admin.aspx");
}
} //.....some code..after this
if (dt.Rows.Count != 0)
{
Session["aname"] = TextBox11.Text;
Response.Redirect("admin.aspx");
}
admin.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["aname"] == null)
{
Response.Redirect("home.aspx");
}
} //some code after this..
protected void logoutbutton_Click(object sender, EventArgs e)
{
Session["aname"] = null;
Session.Abandon();
Session.Clear();
Response.Redirect("home.aspx");
}
NOTE:(things working fine)
1.login working sucessfully
2.logout working sucessfully
3.back button is disabled once loggedout(not going on admin.aspx)
Issue:
When logged in i.e. on admin.aspx ,on clicking back button it redirects to home.aspx which i don't want. i expect it to remain on same admin.aspx
ok.. finally trying all your solutions..this code worked on adding in my masterpage (in head tags)
<script type = "text/javascript" >
function preventBack(){window.history.forward();}
setTimeout("preventBack()", 0);
window.onunload=function(){null};
</script>
full details on this page
You can push the Window History forward to prevent the back button. This has work for me in most cases. Include this JavaScript on your Admin.aspx page.
$(function() {
window.history.forward();
});

How to show login saved in cookie in Page_load event?

I need save login of my Login page in cookie for show every time when page is loaded
I have create for save login in cookie, in Button click event. but, because in the Post Back, Page_Load before button, so when page_load put cookie information in the TextBox, my cookie is empty
What can I do for resolve this?
protected void Page_Load(object sender, EventArgs e)
{
// This time, Cookies["login"].Value is empty
tbLogin.Text = Response.Cookies["login"].Value;
}
protected void Button1_Click1(object sender, EventArgs e)
{
Response.Cookies.Add(new HttpCookie("login", tbLogin.Text));
}
Try using Page.IsPostBack property.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
tbLogin.Text = Response.Cookies["login"].Value;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
Response.Cookies.Add(new HttpCookie("login", tbLogin.Text));
}

Categories