Read and Write Cookies in ASP.NET Core
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 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. 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()
The WriteCookies() action does the job of writing cookies and is shown below:
public IActionResult WriteCookies(string setting,
string settingValue,bool isPersistent)
CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(1);
ViewBag.Message = "Cookie written successfully!";
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
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
Then add Index view and write the following markup into it:
<h1>Specify your preferences :</h1>
<form asp-action="WriteCookies" asp-controller="Home">
<option value="fontName">Font Name</option>
<option value="fontSize">Font Size</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">
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";
ViewBag.FontSize = "22px";
ViewBag.Color = "Blue";
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
The ReadCookies view where these preferences are used is shown below:
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
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!!