19 October 2010 CI Team Edit

imageCookies are a great way to save files on a client like for example registration files ore other stuff. I´m sure some of you who are using the ASP.NET membership system are already familiar with the “stay declared” function. This “HowTo” teach you an easy way how to create and delete a cookie.

Structure

As demo base I use the ASP.NET MVC Framework. That´s what the test page looks like if a cookie is opened:

image

I also registered the time when the cookie was created. (Yes. I´ve been blogging at 3 a.m. in the morning. My poor girlfriend ;) )

If there is no cookie found than it looks like this:

image

The output of the index.aspx runs over the Home Controller:

public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            string cookie = "There is no cookie!";
            if(this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
            {
                cookie = "Yeah - Cookie: " + this.ControllerContext.HttpContext.Request.Cookies["Cookie"].Value;
            }
            ViewData["Cookie"] = cookie;
            return View();
        }

Here it is detected if a cookie exists and if yes than it will be out given.

These two Links guide you to the CookieController:

public class CookieController : Controller
    {

        public ActionResult Create()
        {
            HttpCookie cookie = new HttpCookie("Cookie");
            cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();

            this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Remove()
        {
            if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
            {
                HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
                cookie.Expires = DateTime.Now.AddDays(-1);
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
            }
            return RedirectToAction("Index", "Home");
        }

    }

With the create method it´s quite simple to create a Cookie and lay it down into the response and afterwards it turns back to the Index View.

The remove method controls if a cookie exists and if the answer is positive the Cookie will be deleted directly.

Beware while deleting cookies:

This way to delete a cookie doesn´t work:

this.ControllerContext.HttpContext.Response.Cookies.Clear();

The cookie has to go back to the remove (like it is given in the Cookie Controller) and an expiry date should be given. I´m going to set it on yesterday so the browser has to refuse it directly.

I had to write this down after I was cursing about this subject for a long time. ;)


blog comments powered by Disqus