如果用户没有登录就访问其他页面,那么系统会自动转向登录页,并告诉用户需要先登录。
要实现这样的功能,forms验证就是可以实现的。
这里采用的自定义基类的方式则更加灵活。
1.首先建立基类pageBase.cs
public class PageBase:System.Web.UI.Page //注意这里对System.Web.UI.Page 的继承

...{
public PageBase()

...{

}
public void PageBegin()

...{
HttpCookie cookie2 = Request.Cookies["LoginIdCookie"];

if (cookie2 != null)

...{
string LoginIdcookie = cookie2.Value;
//code here
}
else

...{
Response.Redirect("login.aspx");

}
}
}
2.在除登录页面外的其他页面的load事件中进行如下:
public partial class _Default : PageBase //继承PageBase

...{
protected void Page_Load(object sender, EventArgs e)

...{
this.PageBegin(); //调用基类方法进行判断
}
}
3.Login.aspx.cs
protected void BtnLogin_Click(object sender, EventArgs e)

...{
HttpCookie cookie = new HttpCookie("LoginIdCookie");
cookie.Expires.AddSeconds(20);
cookie.Value = this.TextBox1.Text;
Response.Cookies.Add(cookie);
Response.Redirect("Default.aspx");
}
要实现这样的功能,forms验证就是可以实现的。
这里采用的自定义基类的方式则更加灵活。
1.首先建立基类pageBase.cs
public class PageBase:System.Web.UI.Page //注意这里对System.Web.UI.Page 的继承
...{
public PageBase()
...{
}
public void PageBegin()
...{
HttpCookie cookie2 = Request.Cookies["LoginIdCookie"];
if (cookie2 != null)
...{
string LoginIdcookie = cookie2.Value;
//code here
}
else
...{
Response.Redirect("login.aspx");
}
}
}
public partial class _Default : PageBase //继承PageBase 
...{
protected void Page_Load(object sender, EventArgs e)
...{
this.PageBegin(); //调用基类方法进行判断
}
}
protected void BtnLogin_Click(object sender, EventArgs e)
...{
HttpCookie cookie = new HttpCookie("LoginIdCookie");
cookie.Expires.AddSeconds(20);
cookie.Value = this.TextBox1.Text;
Response.Cookies.Add(cookie);
Response.Redirect("Default.aspx");
}
本文介绍了一种使用ASP.NET实现登录验证的方法。通过创建一个自定义基类PageBase.cs,可以在除登录页面外的所有页面上自动执行登录检查。当用户未登录访问受保护页面时,系统会自动跳转到登录页面。

1986

被折叠的 条评论
为什么被折叠?



