Working on a Black Jack game and I am trying to save the Player's balance as a cookie. I cannot get it to work properly. When exiting the browser and reloading the webpage, the cookie is always null.
I declared the cookie as a static variable so I can access in a later method to send it to the client.
public partial class BlackJack : System.Web.UI.Page
{
public static HttpCookie cookie;
protected void Page_Load(object sender, EventArgs e)
{
cookie = Request.Cookies["Balance"];
if (!IsPostBack)
{
if (cookie != null)
{
PlayerBalance = Convert.ToInt32(cookie.Values["balance"]);
if (PlayerBalance == 0)
{
PlayerBalance = 250;
}
}
else
{
PlayerBalance = 250;
HttpCookie cookie = new HttpCookie("Balance");
cookie.Values.Add("balance", PlayerBalance.ToString());
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
}
PlayerBet = 0;
}
public void Other Method()
{
cookie = Request.Cookies["Balance"];
cookie.Values["balance"] = PlayerBalance.ToString();
Response.Cookies.Add(cookie);
}
Cookies are non-persistent by default. That means as longas you don't specify an expiration date for the cookie the browser clears it, when you close the browser.
So in this case you'll need a persistent cookie, which can be created by setting the Expires
-property:
var cookie = new HttpCookie("Balance");
cookie.Expires = DateTime.Now.AddDays(1);
For more details have a look at this comprehensive article: https://msdn.microsoft.com/en-us/library/ms178194.aspx
But note what @CodeCaster already said: A cookie is only a small piece of text which can be easily modified by the client. So you should consider storing sensitive information elsewhere. Or at least you should consider encrypting your cookies.