How to Work with Cookies in ASP.NET Core

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.

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.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally, select the “Place solution and project in the same directory” check box.
  7. Click Create.
  8. 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.
  9. Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core MVC application.
  10. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  11. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication here either.
  12. 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.

Anjali Punjab

Anjali Punjab is a freelance writer, blogger, and ghostwriter who develops high-quality content for businesses. She is also a HubSpot Inbound Marketing Certified and Google Analytics Qualified Professional.