Introduction
HTTP Cookie is some piece of data that is stored in the user's browser. HTTP cookies play a vital role in the software world. We can store users' related information in cookies and there are many other usages. In asp.net core working with cookies is made easy. I've written a couple of abstraction layers on top of the HTTP cookie object. Cookies are key-value pair collections where we can read, write, and delete using a key.
In ASP.NET, we can access cookies using httpcontext.current but in ASP.NET Core, there is no HTTP context.currently. In ASP.NET Core, everything is decoupled and modular.
Httpcontext is accessible from the Request object and the IHttpContextAccessor interface which is under the "Microsoft.AspNetCore.Http" namespace and this is available anywhere in the application.
Update: I have written a wrapper on top of HTTP Cookie which helps you to ease of use and secure the cookie data. CookieManager is an ASPNET Core Abstraction layer on top of the cookie. Read more here.
Reading Cookie
HttpCookie is accessible from Request. Cookies. Given below is the sample code.
// Read cookie from IHttpContextAccessor
string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["key"];
// Read cookie from Request object
string cookieValueFromReq = Request.Cookies["Key"];
Writing cookie
Here is the code snippet to write cookies. Set method to write cookies. CookieOption is available to extend the cookie behavior.
/// <summary>
/// Set the cookie
/// </summary>
/// <param name="key">Key (unique identifier)</param>
/// <param name="value">Value to store in cookie object</param>
/// <param name="expireTime">Expiration time in minutes</param>
public void Set(string key, string value, int? expireTime)
{
CookieOptions option = new CookieOptions();
if (expireTime.HasValue)
{
option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
}
else
{
option.Expires = DateTime.Now.AddMilliseconds(10);
}
Response.Cookies.Append(key, value, option);
}
Remove Cookie
Delete the cookie by key name.
/// <summary>
/// Delete the cookie by key
/// </summary>
/// <param name="key">Key (identifier of the cookie to delete)</param>
public void Remove(string key)
{
Response.Cookies.Delete(key);
}
CookieOptions
It extends the cookie behavior in the browser.
Options
- Domain: The domain you want to associate with a cookie
- Path: Cookie Path
- Expires: The expiration date and time of the cookie
- HttpOnly: Gets or sets a value that indicates whether a cookie is accessible by client-side script or not.
- Secure: Transmit the cookie using Secure Sockets Layer (SSL) that is, over HTTPS only.
Here is the complete code example to read, write, and delete the cookie.
public class HomeController : Controller
{
private readonly IHttpContextAccessor _httpContextAccessor;
public HomeController(IHttpContextAccessor httpContextAccessor)
{
this._httpContextAccessor = httpContextAccessor;
}
public IActionResult Index()
{
// Read cookie from IHttpContextAccessor
string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["key"];
// Read cookie from Request object
string cookieValueFromReq = Request.Cookies["Key"];
// Set the key value in Cookie
Set("key", "Hello from cookie", 10);
// Delete the cookie object
Remove("Key");
return View();
}
/// <summary>
/// Get the cookie
/// </summary>
/// <param name="key">Key</param>
/// <returns>string value</returns>
public string Get(string key)
{
return Request.Cookies[key];
}
/// <summary>
/// Set the cookie
/// </summary>
/// <param name="key">Key (unique identifier)</param>
/// <param name="value">Value to store in cookie object</param>
/// <param name="expireTime">Expiration time</param>
public void Set(string key, string value, int? expireTime)
{
CookieOptions option = new CookieOptions();
if (expireTime.HasValue)
option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
else
option.Expires = DateTime.Now.AddMilliseconds(10);
Response.Cookies.Append(key, value, option);
}
/// <summary>
/// Delete the key
/// </summary>
/// <param name="key">Key</param>
public void Remove(string key)
{
Response.Cookies.Delete(key);
}
}
I hope you learned how to work with cookies in ASP.NET Core. I have shown you an example of reading, writing, and removing cookie objects.