Quick Overview:
In this blog, you are going to discover the cookies fundamentals and the correct way to utilize them with the ASP.NET Core MVC project. With the information about cookie types, their pros and cons, and use cases, the blog moves to the cookie code blocks to implement. As a result, you will find yourself equipped with the knowledge to configure cookies in an ASP.NET Core web app, within a controller, and in a web API handler.

Working With Cookie in ASP.NET Core

Cookies are considered integral to an application. They help in personalizing experiences and managing sessions and states. Due to this, businesses prefer ASP.NET Core web applications with cookies implementation.

Therefore, as a .NET developer, you should create a new ASP.NET Core web application with cookies functionality. To do so, you don’t have to go anywhere else. In this blog, you can find everything, from cookies fundamentals to their implementation in an ASP.NET Core MVC project and an ASP.NET Core API application.

What are HTTP Cookies?

HTTP cookies are a piece of data consuming KBs of space during web connections. The web server exchanges this data type with the client browser and sometimes even stores it on the browsers. Nowadays, every website and web app uses cookies. Even when you visit a site, a message is displayed that “this site uses cookies.

Primarily, cookies contain user data, which helps to improve the experience. For example, if the cookies access the location, they will use this data to identify the nearest CDN server to boost performance and loading speed.

In addition, the working of cookies depends on its type, such as:

  • Session Cookies: The session cookies maintain the connection between a server and a client browser. These cookies are available for a temporary period until the session server-client session is not terminated.
  • Persistent Cookies: The persistent cookies get stored and are available for extended periods, sometimes until the user doesn’t delete them. The primary purpose of such cookies is to personalize the user experience.

The Pros and Cons of Using Cookies in Dotnet Core Applications

If implementing cookies provides several pros, it also comes with cons.

The pros of cookies include:

  • Easy sessions and state management.
  • Helps in personalizing and improving the experience.
  • Supports authentication and authorization.
  • Optimizes sever-client communication.
  • Helps to save resources and persistence sessions.

The cons of cookies include:

  • It can create security concerns if not used with proper security mechanisms.
  • More network and processing resources are used.
  • Cookies are easily exploited during XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgery) attacks.
  • They have smaller sizes, restricting the data to be stored in them.
  • In some geographical areas, cookies are prohibited due to privacy concerns.

To help you get the best-in-class implementation of cookies, you should always seek .NET development services from a trusted and experienced company. They can help you with proper security configurations and standard compliance, leading to eliminating cookies cons for you.

The Use Case of Cookies in ASP.NET Core MVC Project

In the ASP.NET Core MVC project and ASP.NET Core Web API application, you can utilize cookies for the following purposes.

  • Authenticating the user sessions and providing the permissions per the authorization policies, roles, and responsibilities.
  • To store the user preferences for a particular website, such as theme, language, and more.
  • To retain the products added to the cart. Most eCommerce stores use cookies, and even eCommerce development companies prefer it.
  • To manage the sessions for multiple clients and associated requests.
  • For tracking the user behavior and making an account of daily website visitors.
  • To analyze user engagement and optimize marketing campaigns for better growth.
  • To provide location-based services to a particular target audience.

There are many more use cases of cookies in ASP.NET Core web applications, which top-notch companies, such as Positiwise Software Pvt Ltd, can effortlessly fulfill.

How To Use Cookies in Asp.NET Core Web Application?

To understand the answer to the “How To Use Cookies in ASP.NET,” we will use the Visual Studio IDE 2019 or above version. Users always prefer the latest version because it provides all the required tools and supports significant frameworks.

Once you complete the Visual Studio IDE installation, follow the procedure below in the provided order.

Step 1: Open the Visual Studio IDE and left-click the “Create new Project” option.

Step 2: Choose the ASP.NET Core Web Application from the available templates. These are the pre-built projects with fundamental files and functionalities.

Further, you need to fill in the project details. Also, to move further in the project creation, click on the Next/Crete button.

Step 3: Provide your project details in the “Configure your new project” window. Here, you must provide the name and location where you want to save files.

Step 4: Now, you will view the “Create a New ASP.NET Core Web Application” window. Here, do the following configurations.

  • Choose ASP.NET Core 2.2 and .NET Core for runtime from the drop-down list.
  • Choose “Web Application (Model-View-Controller).
  • Uncheck the “Configure for HTTPS” and “Enable Docker Support” options.
  • Assure that “No Authentication” is selected.

Step 5: Lastly, hit on the Create button. As a result, you will have your ASP.NET Core MVC project.

Now, we will use this project to configure cookies-associated functions in the application. All the code blocks for major cookies functionality are in the further sections. We have divided the cookies implementation into read, write, delete, and access in the ASP.NET Core web app. Let’s have a look at all of them.

#1: Reading a Cookie

To read a cookie, you must configure the application to access Request.Cookies collection. To do so, implement the following code.

string cookie = Request.Cookies["Key"];

In addition, you can also define when the cookie will expire by using the Append method with its overloaded version. It uses a CookieOptions class, which aids in defining the domain, expiration time, path, security policy, and HttpOnly property. 

All the mentioned properties specify the associated domain, cookie path, enabling access over HTTPS connection, cookie expiration time, and cookie availability to the server. You need to define all these properties similarly to the following snippet.

CookieOptions option = new CookieOptions(); 
option.Expires = DateTime.Now.AddMilliseconds(10); 
Response.Cookies.Append(key, value, option); 

#2: Writing a Cookie

Writing a cookie uses the same Append method, in which you have to define a key and a value to pertain to the Request object. To write a cookie, use the following syntax.

Response.Cookies.Append(somekey, somevalue);

#3: Deleting a Cookie

Along with reading and writing, deleting cookies is also necessary. It helps to remove the cookies from memory and free the space for further procedures. For it, you have to define the cookie delete method, similar to the following code block.

Response.Cookies.Delete(somekey);

#4: Accessing HttpContext

In the ASP.NET Core web application, you use HttpContext to access the cookie data. To implement this, you use the HttpContextAccessor class, which extends the functionality by providing the IHttpContextAccessor interface.

To utilize this interface, it has to be registered with dependency injection. Otherwise, the application will not provide cookie access. With the below-provided code, you can enable a singleton service under the Startup class à ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor,
            HttpContextAccessor>();
            //Other code
        }

In addition, you can also define a reference to HttpContext. It will leverage you from the IHttpContextAccessor instance dependency injection. Moreover, you can access this instance using the HomeController, which gets created with every ASP.NET MVC project in Visual Studio IDE.

By implementing the following code, the IHttpContextAccessor instance can be accessed in the HomeController.

public class HomeController : Controller
{
  private readonly IHttpContextAccessor _httpContextAccessor;
  public HomeController(IHttpContextAccessor httpContextAccessor)
  {
     this._httpContextAccessor = httpContextAccessor;
  }   
  //Write your action methods here
}

#5: Writing Cookie in Controller Method

To write cookies using the HomeController, the IActionResult Write method will be used. Under it, you need to define the CookieOptions like the below code.

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");
  }

#6: Reading Cookie in Controller Method

To read the cookie data, you must first implement the write code. Later, you can utilize the following code for viewing it using the controller.

public IActionResult Read(string key)
  {
       ViewBag.Data =
       _httpContextAccessor.HttpContext.Request.Cookies[key];
       return View("ReadCookie");
  }

That’s how you use cookies in the ASP.NET Core MVC project.

Using Cookies in ASP.NET Core API Application

In this section, you will undergo the implementation of cookies in ASP.NET Web API.

For ASP.NET Web API, the cookies are added to the HTTP response using the CookieHeaderValue instance. In addition, System.Net.Http. HttpResponseHeadersExtensions class is also used, as its AddCookies method is required for this implementation. You can add the cookie under the controller by using the below code.

public HttpResponseMessage Get()
{
    var resp = new HttpResponseMessage();

    var cookie = new CookieHeaderValue("session-id", "12345");
    cookie.Expires = DateTimeOffset.Now.AddDays(1);
    cookie.Domain = Request.RequestUri.Host;
    cookie.Path = "/";

    resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
    return resp;
}

With the above code, you have received the cookies through a client request. But, if you want to extract them, you should use the GetCookies method.

string sessionId = "";

CookieHeaderValue cookie = Request.Headers.GetCookies("session-id").FirstOrDefault();
if (cookie != null)
{
    sessionId = cookie["session-id"].Value;
}

Furthermore, if you want structured data to be added to the cookie, the CookieHeaderValue class will be used. The primary purpose of this class is to pass name-value pair list encoded in the URL form data. For implementation, define the class as the following block.

var resp = new HttpResponseMessage();

var nv = new NameValueCollection();
nv["sid"] = "12345";
nv["token"] = "abcdef";
nv["theme"] = "dark blue";
var cookie = new CookieHeaderValue("session", nv); 

resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });

As a result, you will see an output as the below snippet.

Set-Cookie: session=sid=12345&token=abcdef&theme=dark+blue;

Additionally, for reading the sub-value transmitted in the cookie request message, use the CookieState class as demonstrated.

string sessionId = "";
string sessionToken = "";
string theme = "";

CookieHeaderValue cookie = Request.Headers.GetCookies("session").FirstOrDefault();
if (cookie != null)
{
    CookieState cookieState = cookie["session"];

    sessionId = cookieState["sid"];
    sessionToken = cookieState["token"];
    theme = cookieState["theme"];
}

Till now, we have learned the implementation of cookies in the API controller. But there’s also another method in which message handlers are used. This method is way older and preferred than controllers, as it leverages a reading cookie before it gets received or sent by the controller in the request and response.

Now, you will be looking at, for example, where session IDs will be created and added to the cookie in an HTTP request. If there’s no session ID, the handler will automatically create one and add it to the cookie using HttpRequestMessage.Properties. Similarly, the handler will do for a response, i.e., add session ID in the response cookie.

Code for the handler example:

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

public class SessionIdHandler : DelegatingHandler
{
    public static string SessionIdToken = "session-id";

    async protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        string sessionId;

        // Try to get the session ID from the request; otherwise create a new ID.
        var cookie = request.Headers.GetCookies(SessionIdToken).FirstOrDefault();
        if (cookie == null)
        {
            sessionId = Guid.NewGuid().ToString();
        }
        else 
        {
            sessionId = cookie[SessionIdToken].Value;
            try
            {
                Guid guid = Guid.Parse(sessionId);
            }
            catch (FormatException)
            {
                // Bad session ID. Create a new one.
                sessionId = Guid.NewGuid().ToString();
            }
        }

        // Store the session ID in the request property bag.
        request.Properties[SessionIdToken] = sessionId;

        // Continue processing the HTTP request.
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        // Set the session ID as a cookie in the response message.
        response.Headers.AddCookies(new CookieHeaderValue[] {
            new CookieHeaderValue(SessionIdToken, sessionId) 
        });

        return response;
    }
}

The HttpRequestMessage.Properties bag will provide a session ID to the controller.

public HttpResponseMessage Get()
{
    string sessionId = Request.Properties[SessionIdHandler.SessionIdToken] as string;

    return new HttpResponseMessage()
    {
        Content = new StringContent("Your session ID = " + sessionId)
    };
}

That’s how you can use cookies in the ASP.NET Core Web API application. Now, you understand the cookies implementation in ASP.NET Core Web App and Web API. However, ensure that whenever you use any of the provided code, test and debug it before final implementation.

Wrapping Up

Cookies are beneficial for an ASP.NET Core web application. It helps improve user experience, analyze daily website visits, provide location-based services, and maintain sessions in a server-client clean architecture. Every business needs to use cookies and to do so, you need to understand the fundamental syntax, class, and methods used for it.

You can understand how cookies can be used in the ASP.NET MVC project from the code blocks provided above. In addition, the code provides insight into cookie implementation within a controller and for ASP.NET Core Web API. By following the structure, you can use cookies and take advantage of them effortlessly. However, remember to follow all security measures or to onboard an experienced .NET development team.

Parag Mehta

Verified Expert in Software & Web App Engineering

Parag Mehta, the CEO and Founder of Positiwise Software Pvt Ltd has extensive knowledge of the development niche. He is implementing custom strategies to craft highly-appealing and robust applications for its clients and supporting employees to grow and ace the tasks. He is a consistent learner and always provides the best-in-quality solutions, accelerating productivity.

Related Posts