So, you have a web application to build, and you need to track user states as they navigate pages of your website. Or maybe you want to authenticate users, or you are just curious to learn about cookies. Either way, welcome: let’s dive in.
Cookies are small pieces of text that accompany requests and pages as they travel between the web server and the browser.
Cookies are often used in modern web applications development to track user history, states, etc. Most likely, you have come across those pretty pop-ups on sites, informing you that they use cookies when you visit for the first time.
Cookies are transported to and from the server and client machine using the HTTP
protocol.
They can be read, written, and even deleted. If you are super excited like me, let’s write some code to drive this concept in. I will be using the C#
programming language as my weapon of choice.
Essentially, there are two types namely:
When cookies are saved within the browser’s temporary folder on the client’s machine, such cookies are said to be persisted, because information saved can be retrieved at any time, so long the cookies’ expiration date has not elapsed.
Also known as session or in-memory cookies, these are only useable while the browser is open. They are not saved locally on the client’s machine.
In order to implement Cookies in our program, we need the HttpContext
object. The HttpContext
contains these methods that takes one or more arguments needed to set or get cookies and its options.
Some of these methods include:
Void Append(string Key, string value)
: Adds a new cookie and value.
Void Append(string key, string value, CookieOptions options)
:
Adds a new cookie along with its options CookieOptions options
, found in the Microsoft.AspNetCore.Http
namespace.
Void Delete(string key)
: Sets an expired cookie.
Void Delete(string key, CookieOptions options)
: Sets an expired cookie along with a third argument CookieOptions options
.
CookieOptions
options can be accessed from the Microsoft.AspNetCore.Http
namespace and by declaring it’s instance. Some of its options include:
Domain
: Gets or Sets the domain to associate the cookie with.
Expires
: Gets or Sets the expiration date and time for the cookie.
HttpOnly
: Gets or Sets a value indicating if a cookie is accessible by a client-side script.
IsEssential
: Indicates if cookie is essential for the application to function properly.
MaxAge
: Gets or Sets the cookie’s max age.
Path
: Gets or Sets the cookie path.
SameSite
: Gets or Sets the same-site attribute of the cookie.
Secure
: Gets or Sets value that indicates whether to transmit the cookie using Secure Socket Layer (SSL) – that is over Https only.
In order to write cookies, we will need essentially two items, the Response.Cookies
command and the HttpContext
object, which provides a type-safe way to create and manipulate individual HTTP cookies.
Let’s follow these simple steps:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System;
namespace ASPCookies.Controllers
{
public class ASPCookiesController : Controller
{
public IActionResult Index()
{
CookieOptions options = new CookieOptions();
options.Domain = "www.example.com";
options.Expires = DateTime.Now.AddDays(1);
options.HttpOnly = true;
options.IsEssential = true;
options.MaxAge = TimeSpan.FromDays(1);
options.Path = "/";
options.Secure = true;
HttpContext.Response.Cookies.Append("user_Id", "3456", options);
return View();
}
}
}
We will be following pretty much the same steps we used in writing cookies above. The only difference is that we will be using the Request.Cookies
command to read our already set cookies earlier.
As an aside, we will be reading our expected cookie within a control statement.
// --Using NameSpace Here
namespace ASPCookies.Controllers
{
public IActionResult Index()
{
CookieOptions options = new CookieOptions();
options.Domain = "www.example.com";
options.Expires = DateTime.Now.AddDays(1);
options.HttpOnly = true;
options.IsEssential = true;
options.MaxAge = TimeSpan.FromDays(1);
options.Path = "/";
options.Secure = true;
// Checks if the Cookie object contains "user_Id"
if(!HttpContext.Request.Cookies.ContainsKey("user_Id"))
{
// If Not Adds One
HttpContext.Response.Cookies.Append("user_Id","3456", options );
return View();
}
else
{
// Retrieves User Id from Cookie Object
string UserId = HttpContext.Request.Cookies["user_Id"].ToString();
}
}
Cookies cannot be directly deleted from the client’s machine. However, we can remove a cookie by modifying the cookie’s expiration date to a date in the past. When we do this and a request is sent to the path or domain the cookie was registered to, the browser determines that the cookie has expired, and deletes the cookie.
Let’s show this in code:
CookieOptions options = new CookieOptions();
// Sets Expiration Date and Time
options.Expires = DateTime.Now.AddDays(-1);
if(HttpContext.Request.Cookies.ContainsKey("user_Id"))
{
HttpContext.Response.Cookies.Delete("user_Id", options);
return View();
}
As an aside, cookies are not databases. They are to be used lightly, and sensitive data like credit/debit card details and passwords are not meant to be saved in cookies, for obvious security reasons.
If you got here, good job! You now know everything about ASP Cookies, or almost everything.
RELATED TAGS
CONTRIBUTOR
View all Courses