ASP.NET Session & Master Page - c#

I have created MasterPage.aspx and other Pages.I want if user Click on MainPage anywhere on any link or button without Login it must redirect to my Login.aspx.How can i will create session for this ?.I need idea weather i will code in MasterPage.cs Page_load Method or elsewhere ?.MasterPage.aspx{//code here }Login.aspx{//code here }

Use condition like this on master page:
if (Session["LoggedUserName"] == null && !Request.Path.EndsWith("login.aspx"))
{
Response.Redirect("~/your/path/login.aspx");
}
You can also use: MembershipProvider
This can be see here:
Check Session variable and Redirect to login page before page load

You can easily put your code in Page_load event of MasterPage :
if(Session["Login"] == null)
{
Response.Redirect("/Login.aspx");
}
Update :
If you use the MasterPage for all of pages , automatically clicking on all of anchors cause to checking the session, but if you didn't use MasterPage for all, i think you can do this solution :
First Of All, create a class like this :
public class MyPage : Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if(Session["User"] == null)
{
Response.Redirect("/login.aspx");
}
}
}
After that, when creating pages, inheritance them from MyPage class, for example :
public class Default: MyPage

In login page use this code
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtuser.Text == "User" && txtPassword.Text == "Password")
{
Session["username"] = txtuser.Text;
Response.Redirect("Default.aspx");
}
else
{
lblMessage.Text = "Invalid Username/Password";
}
}
In Master page use this code in load event
if(Session["username"]==null)
Response.Redirect("Login.aspx",false);

Try The following code in MasterPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["UserId"] == null)
{
Response.Redirect("Login.aspx");
}
}
}
Hope it will help you well. Let me Know if get Helped.

Related

asp.net login system via c#

i have four pages login.aspx , main.aspx, Sub.aspx, final.aspx. Final page needs authentication to be accessed which i have provided using forms authentication.Logging in through login.aspx it redirects to final.aspx because defaultUrl is set to final.aspx .currently i am going from main.aspx to sub.aspx to final.aspx which redirects to login.aspx after logging in final.aspx. what i want is if i start from login.aspx it should redirect to main.aspx to sub.aspx to final.aspx, jumping from sub.aspx to final.aspx should not redirects to login as already logged in.
But directly accessing the final.aspx should always redirects to login.aspx
login code
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1 .Text =="abc" && TextBox2 .Text =="xyz")
{
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);
}
else
{
Response.Write("w");
}
}
final page code
protected void Page_Load(object sender, EventArgs e)
{
if (User .Identity .IsAuthenticated )
{
Response.Write("welcome");
}
else
{
FormsAuthentication.RedirectToLoginPage();
}
}
web config
<authentication mode ="Forms">
<forms name ="abc" loginUrl ="login.aspx" defaultUrl="final.aspx"/>
</authentication>
I would do it like that:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
Response.Write("welcome");
}
else
{
Response.Redirect("/login.aspx");
}
}
I probably would first show a message "Not authorised. Please log in" with a link to the login page. instead of redirecting.
Hope this helps.
I popose you a better use Session for this case to handle the URL redirecting and authentication.
Try this
To use Session, you need to inherit "Page" in your class :
public class Class1 : Page
Sub page
aspx:
<a id="gotofinal" href="#" OnClick="GoToFinal_Click">Go To Final</a>
aspx.cs:
protected void GoToFinal_Click(object sender, EventArgs e)
{
Session["GoToFinal"] = "Y";
Response.Redirect("final.aspx");
}
Final Page :
protected void Page_Load(object sender, EventArgs e) {
if ((string)Session[IsAuthenticated] == "Y")
{
Session["GoToFinal"] = "";
Response.Write("welcome");
}
else
{
Response.Redirect("login.aspx");
}
}
Login page :
protected void Page_Load(object sender, EventArgs e) {
Session["IsAuthenticated"] = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "abc" && TextBox2.Text == "xyz")
{
Session["IsAuthenticated"] = "Y";
if (!String.IsNullOrEmpty((string)Session["GoToFinal"]) && (string)Session["GoToFinal"] == "Y")
{
Response.Redirect("final.aspx");
}
else
{
Response.Redirect("main.aspx");
}
}
else
{
Response.Write("Login Failed");
}
}
You also need to make logout button in final.aspx to clear the Session[IsAuthenticated]
Session["IsAuthenticated"] = "";
Hope it helps.

check for login in every page

I've multiple web forms in my project. It is simple project. User authentication is done by checking valid username and password and role from database.
In the Page_Load event for every web page I've added this code :
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (Session["username"] == null & Session["role"] == null)
{
Response.Redirect("WebLogin.aspx", false);
Context.ApplicationInstance.CompleteRequest();
}
}
catch (Exception ex) { }
}
so that if someone tries to go to a specific web page via URL, it will check for username and role. If it is null then redirect to login page.
Please can you suggest any other way of doing this, more efficient. It looks very unprofessional to add this code in every code behind page.
Create new class PageBase that inherits Page class and override the onload method for it then add you login check code
public abstract class PageBase : Page
{
protected override void OnLoad(EventArgs e)
{
if (Session["username"] == null & Session["role"] == null)
{
Response.Redirect("WebLogin.aspx", false);
Context.ApplicationInstance.CompleteRequest();
}
}
now for each of your forms just change the page class inheritance from this:
public partial class HomePage : Page
to PageBase like this:
public partial class HomePage : PageBase
This will make your code more organized and clean
you can use asp.net forms authentication.
protected void Page_Load(object sender, System.EventArgs e)
{
if (Context.User.Identity.IsAuthenticated)
{
// User is logged in, continue
}
else
{
//Invalid login...
Session.Clear();
Response.Redirect("~/Login.aspx");
}
}
https://www.asp.net/web-forms/overview/older-versions-security/introduction/an-overview-of-forms-authentication-cs

ASP.NET prevent accessing the homepage before and after logout

I have a login page and a homepage. It's not possible to access homepage without login but after i login and click logout at the homepage. Users are able to access homepage from browser's address row. How can prevent this ? Here is my implementation
Login Click Method at AdminPanelLogin.aspx.cs:
protected void adminLoginButton_Click(object sender, EventArgs e)
{
String adminName = adminNameText.Text;
String password = adminPwdText.Text;
AdminPanelLoginProcess aplp = new AdminPanelLoginProcess();
if (aplp.adminLogin(adminName, password))
{
Session["AdminAuthentication"] = aplp.Admn.AdminID;
Response.Redirect("AdminPanel.aspx");
}
else
{
Response.Write("<script>alert('Login failed !');</script>");
}
}
Logout Click Method at AdminPanel.aspx.cs
protected void adminPanelLogoutLink_Click(object sender, EventArgs e)
{
Session["AdminAuthentication"] = null;
Session.Abandon();
Response.Redirect("AdminPanelLogin.aspx");
}
AdminPanel.aspx.cs Page Load Method:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AdminAuthentication"] == null)
{
Response.Redirect("AdminPanelLogin.aspx");
}
else
{
if (!IsPostBack)
{
showProducts();
showModels();
showShoes();
}
else
{
if (Session["AdminAuthentication"] == null)
{
Response.Redirect("AdminPanelLogin.aspx");
}
}
}
}
By default, the back button does not reload the page but get it from cache. Try to disable cache in AdminPanel.aspx as
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now);
or use any other method from http://www.codeproject.com/Tips/135121/Browser-back-button-issue-after-logout.aspx

Inherit from MasterPage

In a Web Form project, I using MasterPage for user Role and Other-Pages inherit from MasterPage.
I try to use this codes into the Load function in MasterPage :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string MyPage = System.IO.Path.GetFileName(Request.Path);
SqlDataReader RolePageDr = BLL.Users.RolesPage(MyPage);
while (RolePageDr.Read())
{
string Rolepage = RolePageDr["Roles"].ToString();
if (Page.User.IsInRole(Rolepage) != true)
{
Response.Redirect("~/MsgPage.aspx");
}
else
Response.Redirect(MyPage);
}
}
}
But the problem is that when the user redirected to the Other-pages (For Example: AdminPage), this admin page inherited from MasterPage and this Load function run again and a again.
It will run again and again; that is the nature of stateless programming. But what you can do is use session to store it, and then only reload it when session isn't there, as in:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string role;
var sessionValue = Session["Roles"];
if (sessionValue != null)
role = sessionValue.ToString();
else
{
string MyPage = System.IO.Path.GetFileName(Request.Path);
SqlDataReader RolePageDr = BLL.Users.RolesPage(MyPage);
while (RolePageDr.Read())
{
role = RolePageDr["Roles"].ToString();
Session["Roles"] = role;
}
}
if (Page.User.IsInRole(Rolepage) != true)
{
Response.Redirect("~/MsgPage.aspx");
}
else
Response.Redirect(MyPage);
}
}
Session keeps the value and prevents constant checking of the database, but when it expires, the page reloads it and stores it in session again.

Updating parent page from dynamically loaded user control

Hosting page:
protected void Page_Load(object sender, EventArgs e)
{
LoadMyControl(Parameters); //Do it every page load to preserve it's state
}
protected void LoadMyControl(string parameters)
{
plchld.Controls.Clear();
Control userControl = LoadControl("TheUserControl.ascx");
userControl.ID = "userControl1";
plchld.Controls.Add(userControl);
}
Now inside this control, when a button is clicked I want to update ,let's say a Label on the hosting page.
What is the best way to do it? Custom event?
Solution maybe:
In the parent page add:
public Label Actions
{
get { return _Actions; }
set { _Actions = value; }
}
on User Control add the following to the top
<%# Reference Page="../parentpage.aspx" %>
and to change the value just do the following in the user control
ASP.parentpage cc = (ASP.parentpage)this.Parent.Page;
cc.Actions.Text = "hello world";
A UserControl has a Page property which is a reference to the page in which the control is added. You could either cast directly to the known page type that contains the label,
e.g.
protected void Button1_Click(object sender, EventArgs e)
{
var page = Page as _Default;
if (page != null)
{
page.Label1.Text = "Hello World";
}
}
but what would probably be better, is that you decorate you pages where this control can be used with an interface:
public interface ILabelHost
{
void SetLabel(string text);
}
public class _Default : System.Web.UI.Page, ILabelHost
{
...
That way you can use that same logic from before, but on anypage the control is loaded and implements the correct interface:
protected void Button1_Click(object sender, EventArgs e)
{
var host = Page as ILabelHost;
if (host != null)
{
host.SetLabel("Hello World");
}
}

Categories