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.

Hassan SiddiquiPosted Mar 30, 2023, 7:41 AM
Good work I appreciate you on this contribution
Waseem SangrasiPosted Feb 12, 2021, 7:07 PM
I have created separate class of cookie helper, Response is not working there.public class CookieHelper { private readonly IHttpContextAccessor _httpContextAccessor; //public CookieHelper(HttpContextAccessor httpContextAccessor) //{ // _httpContextAccessor = httpContextAccessor; //} public void Set(string key, string value, int? expireTime) { Microsoft.AspNetCore.Http.CookieOptions option = new Microsoft.AspNetCore.Http.CookieOptions(); if (expireTime.HasValue) option.Expires = DateTime.Now.AddMinutes(expireTime.Value); else option.Expires = DateTime.Now.AddMilliseconds(10); _httpContextAccessor.HttpContext.Response.Cookies.Append(key, value); } public string Get(string key) { return _httpContextAccessor.HttpContext.Request.Cookies[key]; } public void Remove(string key) { _httpContextAccessor.HttpContext.Response.Cookies.Delete(key); } }
Srivatshan BrPosted Jan 18, 2021, 8:46 AM
Great its working for me.
Javier RamosPosted Mar 27, 2020, 12:10 PM
Nemi , I made example above example now the stratup.cs you have to do something must be done. I'm not going to use account.
Ali RaxaPosted Feb 29, 2020, 4:29 AM
Nemi, How to check if cookies are enabled in browser in asp.net core.??
Claudinei FerreiraPosted May 2, 2019, 7:29 AM
Nemi, this is great!!! But how do I check if Cookie Exists, like .Net Framework: If(Request.Cookies["Cookie"].Value != null){ //do somenthing}
vysakhan kPosted Apr 10, 2019, 12:33 PM
Hi Nemi, Claim , cookies how both related
maha lakshmiPosted Aug 8, 2018, 1:41 PM
Nice article
Guest UserPosted Aug 8, 2018, 1:37 PM
Good... Easy to implement
Barış YılmazPosted Jul 3, 2018, 6:53 AM
Hi Nemi. i am using .net core web api 2.0 and Oauth2.0 with github account.when i authorize my github account return error and it says " Cookies must be enabled to use GitHub." what can i do . can you help me
Scott SchneiderPosted Jul 2, 2018, 1:50 PM
This would be great but I am using asp.net core 1.1 and the line 43 response is not resolving to any reference. This is a web app and also uses angular. I tried adding system.web as a reference and cannot find it. What are the references?
Maq SaidPosted May 16, 2018, 5:38 PM
Cool! Easy to implement. I found something, you could directly get value stored in Cookie using string cookieValueFromContext = _accessor.HttpContext.Request.Cookies["key"]; You may not require to call Get("Key") to get the value stored in cookie. Cheers
Ajith KumarPosted Mar 15, 2018, 2:38 AM
Hi, Can you tel me about changing cookie domain. When I changed domain, cookie is not getting generated. Thanks
Nicolò CarandiniPosted Dec 10, 2017, 5:48 PM
Please correct the bug on row 28, it should be return Request.Cookies[key]; (without quotes!)