Take advantage of cookies to store and retrieve user-specific information in your ASP.NET Core web application. Credit: Nastco/Thinkstock A cookie is a piece of data typically used to store information about the user and is stored on the user’s computer. In most browsers each cookie is stored as a small file, but in Firefox they are stored all together in a single file. Cookies are represented as key-value pairs, and you can take advantage of the keys to read, write, or delete cookies. ASP.NET Core uses cookies to maintain session state; the cookie that contains the session ID is sent to the client with each request. This article presents a discussion of how we can work with cookies in ASP.NET Core. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. Create an ASP.NET Core MVC project in Visual Studio First off, let’s create an ASP.NET Core MVC project in Visual Studio 2019. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core MVC project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally, select the “Place solution and project in the same directory” check box. Click Create. In the “Create a New ASP.NET Core Web Application” window shown next, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top. Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core MVC application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication here either. Click Create. You should now have a new ASP.NET Core MVC project ready to go in Visual Studio. We’ll use this project in the subsequent sections of this article. Read a cookie in ASP.NET Core You can read a cookie from the Request.Cookies collection. The following code snippet illustrates how you can read a cookie from the Request object in ASP.NET Core. string cookie = Request.Cookies["Key"]; If you would like to specify the expiration time of the cookie, you can use the overloaded version of the Append method as shown in the code snippet given below. CookieOptions option = new CookieOptions(); option.Expires = DateTime.Now.AddMilliseconds(10); Response.Cookies.Append(key, value, option); The CookieOptions class enables you to specify the following additional properties when creating a cookie: Domain — used to specify the domain associated with a cookie Expiration time — used to specify the expiration time of the cookie Path — used to specify the cookie path Security policy — used to specify if the cookie is accessible over HTTPS HttpOnly — used to specify if the cookie is available only to the server Write a cookie in ASP.NET Core To write a cookie you can take advantage of the Append method pertaining to the Request object. The following code snippet illustrates how this can be achieved. Response.Cookies.Append(somekey, somevalue); Delete a cookie in ASP.NET Core To remove a cookie, you can use the Delete method of the Cookies collection pertaining to the Request object. The following code snippet shows how this can be achieved. Response.Cookies.Delete(somekey); Access HttpContext in ASP.NET Core In this section we’ll examine how we can work with cookie data in ASP.NET Core. We’ll need to access the HttpContext to be able to access the Request object. You can access the HttpContext in ASP.NET Core using the IHttpContextAccessor interface. The HttpContextAccessor class implements this interface. First you should register IHttpContextAccessor for dependency injection. The following code snippet illustrates how you can add a singleton service of type HttpContextAccessor in the ConfigureServices method of the Startup class. public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); //Other code } You can take advantage of dependency injection to get a reference to the IHttpContextAccessor instance. This will in turn provide you a reference to HttpContext. The following code snippet illustrates how you can access the IHttpContextAccessor instance in the controller. Note that HomeController is created by default when you create a new ASP.NET Core MVC project in Visual Studio. public class HomeController : Controller { private readonly IHttpContextAccessor _httpContextAccessor; public HomeController(IHttpContextAccessor httpContextAccessor) { this._httpContextAccessor = httpContextAccessor; } //Write your action methods here } Write cookie data in your ASP.NET Core controller method You can use the following method to write cookie data in your controller. public IActionResult Write(string key, string value, bool isPersistent) { CookieOptions options = new CookieOptions(); if (isPersistent) options.Expires = DateTime.Now.AddDays(1); else options.Expires = DateTime.Now.AddSeconds(10); _httpContextAccessor.HttpContext.Response.Cookies.Append (key, value, options); return View("WriteCookie"); } Read cookie data in your ASP.NET Core controller method Once the cookie data has been written successfully, you can use the following method to read cookie data in your controller. public IActionResult Read(string key) { ViewBag.Data = _httpContextAccessor.HttpContext.Request.Cookies[key]; return View("ReadCookie"); } To check if a cookie has been written properly, you can inspect the cookie cache of your web browser. In a future post, we’ll examine how we can work with cookie-based authentication and authorization in ASP.NET Core. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos