ASP.NET Core Working With Cookie

Introduction

HTTP Cookie is some piece of data which 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 Http cookie object. Cookies are key-value pair collections where we can read, write and delete using key.

In ASP.NET, we can access cookies using httpcontext.current but in ASP.NET Core, there is no htttpcontext.currently. In ASP.NET Core, everything is decoupled and modular.

Httpcontext is accessible from Request object and the IHttpContextAccessor interface which is under "Microsoft.AspNetCore.Http" namespace and this is available anywhere in the application. 

Reading Cookie 

HttpCookie is accessible from Request.Cookies. Given below is the sample code,
 

  1. //read cookie from IHttpContextAccessor  
  2. string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["key"];  

  3. //read cookie from Request object  
  4. 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.

  1. /// <summary>  
  2. /// set the cookie  
  3. /// </summary>  
  4. /// <param name="key">key (unique indentifier)</param>  
  5. /// <param name="value">value to store in cookie object</param>  
  6. /// <param name="expireTime">expiration time</param>  
  7. public void Set(string key, string value, int? expireTime)  
  8. {  
  9.    CookieOptions option = new CookieOptions();  

  10.    if (expireTime.HasValue)  
  11.          option.Expires = DateTime.Now.AddMinutes(expireTime.Value);  
  12.    else  
  13.          option.Expires = DateTime.Now.AddMilliseconds(10);  
  14.    
  15.    Response.Cookies.Append(key, value, option);  
  16. }   

Remove Cookie

Delete the cookie by key name.

  1. /// <summary>  
  2. /// Delete the key  
  3. /// </summary>  
  4. /// <param name="key">Key</param>  
  5. public void Remove(string key)  
  6. {  
  7.       Response.Cookies.Delete(key);  
  8. }  
CookieOptions

It extends the cookie behavior in the browser.

Options

  1. Domain - The domain you want to associate with cookie
  2. Path - Cookie Path
  3. Expires - The expiration date and time of the cookie
  4. HttpOnly - Gets or sets a value that indicates whether a cookie is accessible by client-side script or not.
  5. 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.

  1. public class HomeController : Controller  
  2.     {  
  3.         private readonly IHttpContextAccessor _httpContextAccessor;  
  4.   
  5.         public HomeController(IHttpContextAccessor httpContextAccessor)  
  6.         {  
  7.             this._httpContextAccessor = httpContextAccessor;  
  8.         }  
  9.         public IActionResult Index()  
  10.         {  
  11.             //read cookie from IHttpContextAccessor  
  12.             string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["key"];  
  13.             //read cookie from Request object  
  14.             string cookieValueFromReq = Request.Cookies["Key"];  
  15.             //set the key value in Cookie  
  16.             Set("kay""Hello from cookie", 10);  
  17.             //Delete the cookie object  
  18.             Remove("Key");  
  19.             return View();  
  20.         }  
  21.         /// <summary>  
  22.         /// Get the cookie  
  23.         /// </summary>  
  24.         /// <param name="key">Key </param>  
  25.         /// <returns>string value</returns>  
  26.         public string Get(string key)  
  27.         {  
  28.             return Request.Cookies["Key"];  
  29.         }  
  30.         /// <summary>  
  31.         /// set the cookie  
  32.         /// </summary>  
  33.         /// <param name="key">key (unique indentifier)</param>  
  34.         /// <param name="value">value to store in cookie object</param>  
  35.         /// <param name="expireTime">expiration time</param>  
  36.         public void Set(string key, string value, int? expireTime)  
  37.         {  
  38.             CookieOptions option = new CookieOptions();  
  39.             if (expireTime.HasValue)  
  40.                 option.Expires = DateTime.Now.AddMinutes(expireTime.Value);  
  41.             else  
  42.                 option.Expires = DateTime.Now.AddMilliseconds(10);  
  43.             Response.Cookies.Append(key, value, option);  
  44.         }  
  45.         /// <summary>  
  46.         /// Delete the key  
  47.         /// </summary>  
  48.         /// <param name="key">Key</param>  
  49.         public void Remove(string key)  
  50.         {  
  51.             Response.Cookies.Delete(key);  
  52.         }  
  53.     }   

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.

Up Next
    Ebook Download
    View all
    Learn
    View all