当页面被重新加载到asp.net时,Cookie不起作用
本文关键字:net asp 不起作用 Cookie 加载 新加载 | 更新日期: 2023-09-27 17:59:21
当我的登录按钮被点击时,它应该会创建这个cookie
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HttpCookie testCookie = new HttpCookie("UserInfo");
testCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(testCookie);
}
}
protected void NavigationMenu_MenuItemClick(object sender, MenuEventArgs e)
{
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
}
protected void LoginView1_ViewChanged(object sender, EventArgs e)
{
}
protected void btnLogIn_Click(object sender, EventArgs e)
{
if (UserEmail.Text == "example@hotmail.com" && TextBox1.Text == "qwerty1")
{
HttpCookie cookie = Request.Cookies["UserInfo"];
cookie["userName"] = UserEmail.Text;
cookie["booleanCheck"] = "true";
Response.Cookies.Add(cookie);
Response.Redirect(Request.RawUrl);
}
else
{
ErrorMessage.Visible = true;
ErrorEmail.Visible = true;
ErrorPassword.Visible = true;
}
}
}
}
然后,上面保存的cookie应该用于设置网站的主页面。
public partial class _Default : System.Web.UI.Page
{
Boolean found = false;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_PreInit(object sender, EventArgs e)
{
String signedInCheck = "false";
HttpCookie cookie = Request.Cookies["userInfo"];
if (cookie != null)
{
signedInCheck = cookie["booleanCheck"];
}
try
{
if (signedInCheck != "true")
this.Page.MasterPageFile = "~/Site.Master";
else
this.Page.MasterPageFile = "~/LoggedIn.Master";
}
catch (Exception ex)
{
}
}
}
}
此代码用于切换到第二个母版页,但当页面被重新定向,甚至返回到其自身时,它会切换回第一个母版页面。如何更改此设置,以便在登录时始终显示第二个主页面。
您需要添加Cookie 的天数或过期时间
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["Font"] = "Arial";
myCookie["Color"] = "Blue";
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
试试看它是否适合你。
URL供您参考http://msdn.microsoft.com/en-us/library/ms178194.aspx