当页面重新加载asp.net时,Cookies不起作用

时间:2014-04-22 04:56:32

标签: c# asp.net cookies response.redirect

单击我的登录按钮时,应该创建此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)
        {

        }
    }
}
}

此代码可以切换到第二个母版页,但当页面重新编辑时,甚至回到自身,它会切换回第一个母版页。如何更改此设置,以便在您登录时始终显示第二个母版页。

1 个答案:

答案 0 :(得分:0)

您需要添加Cookie的天数或到期时间

HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["Font"] = "Arial";
myCookie["Color"] = "Blue";
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);

试一试,看看它是否适合你。

您参考的网址 http://msdn.microsoft.com/en-us/library/ms178194.aspx