Bạn có thể thử mã này, Trong trường hợp tải chủ trang viết mã này, thêm một tài sản
public bool m_bLoginRequired = true;
public bool IsLoginRequired
{
get { return m_bLoginRequired; }
set { m_bLoginRequired = value; }
}
try
{
// Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
Response.Cache.SetNoStore();
if (IsLoginRequired==true)
{
if (Session.IsNewSession || HttpContext.Current.Session["Username"] == null)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage("Session Expired");
Response.End();
}
}
}
catch (Exception ex)
{
throw (ex);
}
bây giờ trong trang Login bạn cần phải viết mã này
FormsAuthentication.SetAuthCookie(this.txt_UserName.Text.Trim(), false); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, this.txt_UserName.Text.Trim(), DateTime.Now, DateTime.Now.AddMinutes(10), false, "HR");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
cookie.Name = "jay";
Session["UserName"] = txt_UserName.Text.Trim();
Response.Cookies.Add(cookie);
txt_UserName.Text = "";
txt_Password.Text = "";
Response.Redirect("HomePage2.aspx");
bây giờ bạn ave để thêm sự kiện pageinit trong trang đăng nhập
protected void Page_PreInit(object sender, EventArgs e)
{
Master.IsLoginRequired = false;
}
nếu bạn muốn người dùng có thể truy cập một trang chưa được ủy quyền sau đó trong sự kiện pageinit của trang đó
đặt Master.IsLoginRequired=false;
cũng chỉ định thông tin đăng nhập trong tệp web.config
.
Nguồn
2009-03-20 13:26:04
Bạn có ý nghĩa gì bởi 'có thể sửa chữa và hiệu quả hơn'? Có gì sai với phương pháp bạn đã phác thảo ở trên? –
Tôi cho rằng ecleel có nghĩa là "linh hoạt" khi tôi trả lời dưới đây - sử dụng Web.Configs có thể là một nỗi đau nếu bạn đang làm điều này với các trang động hoặc dựa trên ngày một trang được đăng ví dụ (tức là hạn chế quyền truy cập vào các trang lưu trữ) –