HowTo: create and remove Cookies with ASP.NET MVC

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. ;)

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by

Currently there is no additional info about this author.

2 Responses

  1. I tested your method, but the cookie is not saved.

    Reply
  2. It worked for me but I had to set the Expires field after creating the cookie.

    Reply

Comment on this post

Recent Posts

  • How to access an Azure Website with the local IIS Manager

      Since the end of February it is possible to access an Azure Website with the IIS Manager. Although the Azure Management site offers some information’s there are more details visible at the IIS Manager.   For the connection you will need an IIS Manager and the IIS Manager for Remote Administration Extension. It’s also […]

  • image1929-570x143_thumb.png
    Create and validate own Json-Web-Tokens (JWTs)

    If you are interested in web authentication you probably have heard about JSON Web tokens (JWT). What is a JWT? Maybe I’m not using the correct security termination but however: JWTs are used to exchange claims between two systems. For example: You want to log on to a service (like Facebook, Twitter, etc.) and want […]

  • Micro-Optimization: how to shrink or „embed“ pictures

      I’m currently working on the “CodeInside Dashboard” and since the page structure isn’t that difficult it should be possible to fulfill all of Google Pagespeed or Yahoos YSlow recommendations. One of the rules was to optimize the 4 PNGs that are embedded on the page.   Before – without optimization: Below you can see […]

  • image1979-570x194.png
    Move to Windows Azure – VMs, Word Press Migration, DNS changes

    Since mid January this blogs runs on a WordPress installation in an Azure VM. Because I always thought that the subject is quite complicated this blogpost offers a view behind the scenes. Why this move? So far this blog (both German and English Version) runs on a hoster somewhere in Germany. The main problem with this […]

  • Windows Azure Active Directory – CRUD for users and groups

      Windows Azure Active Directory? If you are not informed about the subject I recommend you to have a look on this Azure Info site. Which resources are there? The Azure AD contains the following entities: - Users - Groups - Contacts - Roles Access to the directory or on the “directory graph” Although the […]

Support us