Meditation and Mindfulness for Software / IT Professionals. Conducted by Bipin Joshi in Thane. Read more...

Read and Write Cookies in ASP.NET Core 1.0

Storing and retrieving small pieces of information in cookies a common requirement in many web applications. This article explains with an example how ASP.NET Core 1.0 deals with cookies. You will learn to read and write cookies using ASP.NET Core. You will also learn to configure the cookie properties such as expiration time.

The application you develop in this article looks like this:

As you can see the page allows you to specify certain preferences such as font name, font size and color. You can select a preference from the dropdown list and specify its value in the textbox. Clicking on the Write Cookie button saves that preference in a cookie. The Is Persistent checkbox controls whether the cookies are to be stored on the local disk so that they are be read during a different browser session. The read cookies link takes you to another page where the preferences are read and applied to a sample HTML markup.

Begin by creating a new ASP.NET Core Web Application using Visual Studio 2015. Then open the HomeController and add three actions to it - Index(), WriteCookies() and ReadCookies().

The Index() action is quite straightforward and simply returns the Index view to the browser.

public IActionResult Index()
    return View();

The WriteCookies() action does the job of writing cookies and is shown below:

public IActionResult WriteCookies(string setting,
              string settingValue,bool isPersistent)
    if (isPersistent)
        CookieOptions options = new CookieOptions();
        options.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Append(setting, settingValue,options);
        Response.Cookies.Append(setting, settingValue);
    ViewBag.Message = "Cookie written successfully!";
    return View("Index");

The WriteCookies() method receives three parameters namely setting, settingValue and isPersistent through model binding. The setting paremeter will be the value selected in the dropdown list. The settingValue parameter will be the value entered in the textbox and isPersistent will indicate whether isPersistent checkbox is checked or not.

Inside, the code checks the value of isPersistent boolean parameter. If it is true an object of CookieOptions class (Microsoft.AspNetCore.Http namespace) is created. The CookieOptions class allows you to specify the properties of the cookie such as the following:

  • Domain (domain associated with the cookie)
  • Expires (when the cookie should expire)
  • Path (specify path where cookie is applicable)
  • Secure (cookie is sent only on https channel)
  • HttpOnly (client side script can't access the cookie)

In the above example, you set the Expires property of the cookie to one day from now. This way the cookie will be persisted on the client machine for one day. Then a cookie is written to the response using the Append() method of the Cookies collection. The Append() method accepts key, value and CookieOptions object.

The else block of the code simply appends a cookie by setting its key and value (no CookieOptions object is passed).

A ViewBag message indicates to the user that the preference is stored successfully.

Then add Index view and write the following markup into it:

<h1>Specify your preferences :</h1>
<form asp-action="WriteCookies" asp-controller="Home">
    <select name="setting">
        <option value="fontName">Font Name</option>
        <option value="fontSize">Font Size</option>
        <option value="color">Color</option>
    <input type="text" name="settingValue" />
    <input type="checkbox" name="isPersistent" 
           value="true" /> Is Persistent?
    <input type="submit" value="Write Cookie" />


    <a asp-action="ReadCookies" asp-controller="Home">
       Read Cookies

The Index view renders a <form> shown earlier using ASP.NET Core tag helpers and input elements. It also outputs the Message property from ViewBag. A Read Cookies link takes the user to a test page where  preferences are applied.

Now, add ReadCookies() action to the HomeController and write the following code to it :

public IActionResult ReadCookies()
    ViewBag.FontName = Request.Cookies["fontName"];
    ViewBag.FontSize = Request.Cookies["fontSize"];
    ViewBag.Color = Request.Cookies["color"];

        ViewBag.FontName = "Arial";
    if (string.IsNullOrEmpty(ViewBag.FontSize))
        ViewBag.FontSize = "22px";
    if (string.IsNullOrEmpty(ViewBag.Color))
        ViewBag.Color = "Blue";
    return View();

The ReadCookies() action reads three cookies with the help of their respective keys. This is done using Cookies collection of the Request object. The cookie values are stored in ViewBag properties. A series of if statements check whether a particular preference is empty and if so assign a default value to it.

The ReadCookies view where these preferences are used is shown below:

<div style="font-family:'@ViewBag.FontName';
    Hello World! 

 The ReadCookies view consists of a <div> element whose style attribute makes use of font name, font size and color specified in the respective ViewBag properties.

This completes the application. Run it and specify values to the three preferences. Don't check the Is Persistent checkbox while saving the values. Then click on the Read Cookies link. You should something similar to this:

Then run the application again and repeat the process by checking the Is Persistent checkbox. If you observe the browser's cookie cache you will find the three cookies there:

That's it for now! Keep coding!!

Bipin Joshi is a software consultant, an author and a yoga mentor having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 20 Jun 2016

Tags : ASP.NET ASP.NET Core MVC .NET Framework C#