Cookies in ASP.NET Core MVC

Cookies in ASP.NET Core MVC

In this article, I am going to explain how to store data in browser cookies using ASP.NET Core MVC Application. So, at the end of this article, you will understand how to set a cookie and then read it again afterward to be able to share information about a specific client between multiple requests.

The Web communication between a server and a client uses the HTTP protocol, which is a stateless protocol. This means that a user will not automatically share information between two requests. Instead, cookies or sessions must be used to share the information between the requests. This is useful in situations such as keeping a user logged in between requests.

Nowadays, most server-side technologies have built-in cookie support, including the ASP.NET Core MVC framework. Dealing with cookies is made easy by the HttpContext class. 

What is a Cookie?

A cookie is a small text file that a website stores on a user’s computer or mobile device when they visit the site. This file contains information that can be used to identify the user, such as their login status or preferences, and is sent back to the website with every subsequent request. Typically, it’s used to tell the web server if two requests are coming from the same web browser.

Cookies are stored in the form of key-value pairs, and you can take advantage of the keys to read, write, or delete cookies. For a better understanding of how cookies work, please have a look at the following diagram.

What is a Cookie?

Cookies work as follows:
  1. First, the client (Web Browser) will send the HTTP Request to the Server.
  2. Once the server receives the request, it will process the request and generate the response. Along with the generated response, it will create the cookie and send it to the client with the response header. You can set multiple cookies also as per your requirement. For each cookie, it will add one Set-Cookie in the response header.
  3. Once the client receives the response, from the next request onwards (as long as the cookie is not expired and not deleted), the client will send the HTTP Request along with the cookie in the request header. The client will send only the Cookie object in the request header containing all cookie data.
  4. Once the server receives the request, it will check the cookie and accordingly process the request.
Types of Cookies:

There are two types of Cookies. They are as follows:

  1. Persistent Cookie: Persistent cookies are long-term cookies that can be stored across multiple sessions. Persistent cookies store login and user preferences for a personalized experience across sessions.
  2. Non-Persistent or Session Cookie: Session cookies are temporary cookies stored on a user’s computer while browsing a website. These cookies are used to maintain a session state and are deleted once the user closes their browser or navigates away from the website.

Note: In this article, I am going to discuss Persistent Cookies, and in our next article, I am going to discuss Session Cookies.

How do you Write, Read and Delete Cookies in ASP.NET Core MVC?

Cookies in ASP.NET Core MVC are a fundamental mechanism for storing small pieces of information on the client side, typically in a user’s web browser. Cookies are used to maintain state, track user interactions, and provide personalized experiences in web applications. ASP.NET Core MVC provides built-in support for working with cookies to enable various scenarios, such as authentication, session management, and tracking user preferences.

Here are some key aspects of cookies in ASP.NET Core MVC:

  1. Storage on the Client Side: Cookies are small text data sent from the server and stored on the client side (in the user’s browser). Each cookie is associated with a specific domain and path on the server.
  2. State Maintenance: Cookies are commonly used to maintain the state between requests. For example, they can track whether a user is authenticated or store user preferences across sessions.
  3. Authentication and Authorization: Cookies are often used for authentication purposes. When a user logs in, the server can issue a cookie containing a unique identifier or token that represents the authenticated user. Subsequent requests can include the cookie to confirm the user’s identity and access rights.
  4. Session Management: Cookies can be used to maintain session information on the client side. ASP.NET Core provides session management features that use cookies to store session identifiers.
  5. Personalization: Cookies can be used to store user preferences or settings. For example, a website might remember a user’s language preference or display preferences using cookies.
  6. Tracking and Analytics: Cookies are used to track user interactions and behavior on websites. This data can be used for analytics, tracking user journeys, and providing targeted advertisements.
  7. Expiration and Persistence: Cookies can have expiration dates or be set to be persistent. Session cookies expire when the user closes the browser, while persistent cookies remain on the user’s system for a specified period.
  8. Secure and HttpOnly Flags: Cookies can be configured to be secure (only sent over HTTPS connections) and HttpOnly (not accessible via JavaScript, improving security against cross-site scripting attacks).

ASP.NET Core uses cookies to maintain the session state; the cookie that contains the session ID is sent to the client with each request.

Writing a Cookie in ASP.NET Core MVC:

To create a cookie in ASP.NET Core MVC, create an instance of the CookieOptions class, set the expiry date using Expires property, then add the cookie to Response.Cookies collection using the Append method with name, value, and CookieOptions object as parameters as follows.

CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Append(“UserId”, “1234567”, options);
Response.Cookies.Append(“UserName”, “pranaya@dotnettutotials.net”, options);

The CookieOptions class provides additional properties that can be set when creating a cookie, including:

  1. Domain: Gets or sets the domain to associate the cookie with.
  2. Expiration time: Gets or sets the expiration date and time for the cookie.
  3. Path: Gets or sets the cookie path. Creates a default cookie with a path of ‘/’.
  4. Secure: Gets or sets a value indicating whether to transmit the cookie using Secure Sockets Layer (SSL) over HTTPS.
  5. HttpOnly: Gets or sets a value that indicates whether a cookie is accessible by client-side script. If its value is set to true, then it can’t be accessed from JavaScript.
  6. MaxAge: Gets or sets the max age for the cookie.
  7. IsEssential: Indicates if this cookie is essential for the application to function correctly. If true, then consent policy checks may be bypassed. The default value is false.
Reading a Cookie in ASP.NET Core MVC:

We need to use the Request.Cookies collection to read a cookie in ASP.NET Core MVC, and we need to pass the key as follows:

string? UserName = Request.Cookies[“UserId”];
int? UserId = Convert.ToInt32(Request.Cookies[“UserName”]);

Deleting a Cookie in ASP.NET Core MVC:

We need to use Request.Cookies.Delete to delete a cookie in ASP.NET Core MVC by passing the key name as follows.

Response.Cookies.Delete(“UserId”);
Response.Cookies.Delete(“UserName”);

Modifying the Home Controller:

Next, modify the HomeController as follows. As you can see, we have created two const variables to store the cookie keys. Within the Index Action method, we are storing the user data in the cookie object. Further, if you notice, we are accessing the cookie data from the About action method.

using Microsoft.AspNetCore.Mvc;
namespace SampleMVCWeb.Controllers
{
    public class HomeController : Controller
    {
        const string CookieUserId = "UserId";
        const string CookieUserName = "UserName";
        public IActionResult Index()
        {
            //Let us assume the User is logged in and we need to store the user information in the cookie
            CookieOptions options = new CookieOptions();
            options.Expires = DateTime.Now.AddDays(7);
            Response.Cookies.Append(CookieUserId, "1234567", options);
            Response.Cookies.Append(CookieUserName, "pranaya@dotnettutotials.net", options);

            return View();
        }

        public string About()
        {
            //Accessing the Cookie Data inside a Method
            string? UserName = Request.Cookies[CookieUserName];
            int? UserId = Convert.ToInt32(Request.Cookies[CookieUserId]);

            string Message = $"UserName: {UserName}, UserId: {UserId}";
            return Message;
        }

        public IActionResult Privacy()
        {
            return View();
        }

        public string DeleteCookie()
        {
            // Delete the cookie from the browser.
            Response.Cookies.Delete(CookieUserId);
            Response.Cookies.Delete(CookieUserName);

            return "Cookies are Deleted";
        }
    }
}
How to Access the Cookie Object in a View?

In order to use the Cookies inside a View, we need to inject the IHttpContextAccessor implementation into our view and use it to get the HttpContext and Request objects from that. For this, we need to add the following two statements in our view. The first statement adds the namespace and the second statement injects the IHttpContextAccessor, and uses this HttpContextAccessor. We can access the HttpContext and Session objects.

@using Microsoft.AspNetCore.Http;

@inject IHttpContextAccessor HttpContextAccessor

Modifying the Index.cshtml view:
@using Microsoft.AspNetCore.Http;
@inject IHttpContextAccessor HttpContextAccessor

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-left">
    <b>User Name:</b> @HttpContextAccessor?.HttpContext?.Request.Cookies["UserName"]
    <br />
    <b>User Id:</b> @HttpContextAccessor?.HttpContext?.Request.Cookies["UserId"]
</div>
Modifying the Privacy.cshtml view:
@using Microsoft.AspNetCore.Http;
@inject IHttpContextAccessor HttpContextAccessor

@{
    ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<div class="text-left">
    <b>User Name:</b> @HttpContextAccessor?.HttpContext?.Request.Cookies["UserName"]
    <br />
    <b>User Id:</b> @HttpContextAccessor?.HttpContext?.Request.Cookies["UserId"]
</div>

With the above changes in place, you will get the following exception if you run the application. This is because we are using the HttpContextAccessor service, but we have not yet configured this service into the built-in IOC container.

Cookies in ASP.NET Core MVC

Now, we need to configure the HttpContextAccessor service within the Main method of the Program class. The following piece of code does the same.

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

So, modify the Main method of the Program class as follows:

namespace SampleMVCWeb
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();
            //Adding the IHttpContextAccessor servive to the Dependency Injection IOC Container
            builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}

Now, run the application, and by default, it will execute the Index Action Method of the Home controller, and then it renders the Index view where you can see the cookie data as shown in the below image.

Cookies in ASP.NET Core MVC Application

Now, if you open the browser developer tool and go to the Network tab, inspect the request, then you will see in the response header two cookies are being sent by the server, as shown in the below image. The cookie contains the key name, value, and expiration date. As you can see, cookies store the user information in plain text which is not good from the security point of view.

how to store data in browser cookies using ASP.NET Core MVC Application

If you visit the Privacy page, it will render the cookie data, as shown in the image below.

Cookies in ASP.NET Core MVC Application

Now, if you go to the Network tab and inspect the request using the browser developer tool and then you will see that along with the request, the web browser is now sending the cookie in the request header, as shown in the below image. This will happen for each and every request sent from the client to the server.

how to store data in browser cookies using ASP.NET Core MVC Application

If you visit the About page, it will also render the session data, as shown in the image below.

how to store data in browser cookies using ASP.NET Core MVC Application

If you visit the DeleteCookie page, it will delete the cookies, and you will get the following message, as shown in the image below.

Cookies in ASP.NET Core MVC Application

If you verify the response header, you will see that the cookie values are being deleted, as shown in the image below.

how to store data in browser cookies using ASP.NET Core MVC Application

If you visit the About and Privacy page, you will not see the cookie data shown in the image below.

Cookies in ASP.NET Core MVC Application

Advantages and Disadvantages of using Cookies in ASP.NET Core MVC:

Cookies are a versatile tool in web development, and they have both advantages and disadvantages when used in ASP.NET Core MVC applications. Understanding these pros and cons can help you make informed decisions about when and how to use cookies in your projects.

Advantages of Using Cookies in ASP.NET Core MVC:
  1. State Management: Cookies enable you to maintain state across multiple HTTP requests, allowing you to track user sessions, authentication status, and user preferences.
  2. User Personalization: Cookies can store user-specific preferences, such as language settings, themes, or layout choices, providing a more personalized user experience.
  3. Session Persistence: Cookies can persist information across browser sessions, making it possible to maintain user data even after they close and reopen the browser.
  4. Authentication and Authorization: Cookies are commonly used for implementing authentication mechanisms, allowing you to maintain user sessions and keep users logged in.
  5. Ease of Use: Cookies are simple to implement and use. ASP.NET Core provides easy-to-use APIs for working with cookies, making reading, writing, and managing cookie data straightforward.
  6. Cross-Site Communication: Cookies can be used to share data between different applications or subdomains under the same parent domain.
  7. Server Resource Savings: Storing user-related data on the client side reduces the need for the server to manage the session state, potentially improving server performance and scalability.
Disadvantages of Using Cookies in ASP.NET Core MVC:
  1. Data Size Limit: Cookies have size limitations (usually around 4KB), which may restrict the amount of data you can store in them.
  2. Security Concerns: Cookies are stored on the client side and can be tampered with by users or malicious actors. Proper security measures, such as encryption and secure flags, are essential to mitigate risks.
  3. Privacy Concerns: Cookies can be used to track user behavior, leading to potential privacy concerns. Regulations like GDPR impose strict rules on how cookies can be used for user tracking and data collection.
  4. Network Overhead: Cookies are sent with every HTTP request, increasing network traffic. This can impact performance, especially if large amounts of data are being transmitted.
  5. Cross-Site Scripting (XSS) Vulnerabilities: If not properly secured, cookies can be vulnerable to XSS attacks, where malicious scripts are injected into a web application.
  6. Cross-Site Request Forgery (CSRF) Vulnerabilities: Cookies can be exploited in CSRF attacks, where a malicious site performs actions on behalf of the user without their consent.
  7. Browser Compatibility: While cookies are widely supported, they can be disabled or restricted by users, limiting their effectiveness in some scenarios.
  8. Limited Storage Duration: Cookies have expiration times and can be cleared by the user or browser, potentially leading to data loss.

When using cookies in ASP.NET Core MVC, it’s crucial to consider these advantages and disadvantages and make informed decisions based on your application’s requirements, security needs, and privacy considerations. In some cases, you may also explore alternative data storage options, such as local, session, or server-side, to address specific challenges or limitations posed by cookies.

When to use Cookies in ASP.NET Core MVC?

Cookies in ASP.NET Core MVC can be used in various scenarios to enhance user experience, manage state, and provide personalized interactions. Here are some situations where using cookies is appropriate:

  1. Authentication and Authorization: Cookies are commonly used for implementing authentication and maintaining user sessions. When a user logs in, a cookie with a secure token or identifier can be issued, and subsequent requests can include the cookie to authenticate the user and grant access to authorized resources.
  2. User Preferences: Cookies can store user-specific preferences, such as language preferences, theme choices, or display settings. This allows you to provide a personalized experience for each user.
  3. Remember Me Functionality: Cookies can be used to remember a user’s login credentials between sessions, offering a “Remember Me” feature that enhances user convenience.
  4. Shopping Carts: Sessions are often employed to manage shopping cart data. You can store information about items added to the cart and their quantities, ensuring that the cart contents are retained between page views and interactions.
  5. Form Data Persistence: Sessions can be used to temporarily store form data between multiple steps of a multi-page process. This is useful for scenarios like multi-step forms or wizards.
  6. Session Management: Cookies can be used to manage user sessions, enabling you to maintain user-related data across multiple requests without relying solely on server-side session management.
  7. Tracking User Behavior: Cookies are commonly employed to track user interactions and behavior on a website. This data can be used for analytics, user profiling, and providing personalized recommendations.
  8. Cross-Site Communication: Cookies can facilitate communication between different applications or subdomains under the same parent domain, enabling data sharing and coordination.
  9. Visitor Counting: Cookies can be used to count and track the number of visits or unique visitors to a website.
  10. Advertisement and Marketing: Cookies can help track user engagement with advertisements and marketing campaigns, enabling targeted advertising and a better understanding of user interests.
  11. Single Sign-On (SSO): Cookies can be utilized in single sign-on scenarios to allow users to authenticate once and access multiple applications without repeated logins.
  12. Location or Geographical Information: Cookies can store location-related data to provide location-based services or recommendations.

Remember that while cookies offer valuable capabilities, they also come with security and privacy considerations. Ensure you follow best practices for secure cookie handling, implement proper encryption and validation, and adhere to privacy regulations such as GDPR when collecting user data through cookies.

In scenarios where cookies might not be suitable due to size limitations, security concerns, or user preferences, you can explore alternatives such as local storage, session storage, or server-side data storage mechanisms provided by ASP.NET Core, depending on your specific needs.

In the next article, I am going to discuss Sessions in ASP.NET Core MVC Applications with Examples. In this article, I try to explain Cookies in ASP.NET Core MVC Applications with Examples. I hope you enjoy this Cookie in ASP.NET Core MVC Application article.

2 thoughts on “Cookies in ASP.NET Core MVC”

Leave a Reply

Your email address will not be published. Required fields are marked *