简体   繁体   中英

Cookies dont work when page gets reloaded asp.net

When my login button is clicked it should create this 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;
        }
    }
}

}

Then the cookie that was saved above should be used to set the master page of the site.

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)
        {

        }
    }
}
}

This code works to switch to the second master page but when the page gets redrirected, even back to itself, it switches back to the first master page. How to change this so that when you are logged in you always display the second masterpage.

You need to add Days or expiration of Cookie

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

Give it a try and see if it works for you.

URL for you reference http://msdn.microsoft.com/en-us/library/ms178194.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM