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.

  • http://www.virtualgraffiti.com K Prock

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

  • http://Website J Spellman

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

  • Ali Naeem

    same , cookie not saved

Recent Posts

  • HowTo: make out Retweet-counter in a random URL

      Twitter offers some interesting functions with the integration of the twitter button – every user can see how often the website has been retweeted and he can do the same with just one click. But of course the whole thing has his price: - The integration of the Twitter JavaScript makes the whole data […]

  • Time-controlled Azure WebJobs – Azure as easy as it get‘s

        While still in development the Azure WebJob SDK offers some cool features for procession and supply of information. A good example is the sample that observes the Azure Queue and processes an item as soon as it spots one.   Scenario: time-controlled activities – without queue and so on My scenario was quite […]

  • image2021-570x194_thumb.png
    HowTo: Create RSS Feeds with ASP.NET MVC

    I’ve already written about how to consume RSS or Atom Feeds with the SyndicationFeed (in German, sry) but todays post is about how to create or publish an own feed. Beside the age of the feed standard and the much defamation from Facebook, Twitter and Google on RSS/Atom I consider this easy to consume API […]

  • image1997-311x194_thumb.png
    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 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 possible to […]

  • 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 […]

Support us