Cookies in ASP.NET

17 december 2021 om 10:00 by ParTech Media - Post a comment

The world is going through a massive digital transformation; the traditional ways of handling things are no longer relevant today. Efficiency and convenience are being given utmost importance.

For example, we are able to buy our daily essentials through e-commerce websites.

We are able to transfer money through internet banking.

We are able to watch newly released movies through OTT platforms, and so on.

Whenever we talk about digital transformation, we cannot ignore the part that involves user interaction and user interface. The User Interface (UI) plays a key role in passing the information promptly to the users. And when it comes to UIs, the better the convenience and handling, the better the experience would be.

Even small things matter when it comes to the UIs. For example, the right placement of buttons can be a very important feature for a particular group of users. In short, to attract and retain users, it is necessary to have a great user experience.

Let’s pick another example. You have logged in to an e-commerce website and you are browsing across different product pages. You even add a few items to the cart. Now, when you close the browser and reopen it again, how would you react if the website asks for login again for adding the same items back to the cart. Wouldn’t it be painful? Now if you are the business that owns that website, then get ready to lose some customers due to poor customer experience.

The only solution is to store the information about the user so that the details are automatically retrieved without any input from the user. And the best way to achieve this is through cookies. In this post, we will understand cookies and how they can be implemented in ASP.NET MVC-based web applications.

Table of contents

  1. Introduction to cookies
  2. A practical example of creating and accessing cookies
  3. Conclusion

Introduction to cookies

Cookies are small data files that are stored on the user’s computer. It is developed and designed to pass website-specific information between the website and browser. This means each website can have its own set of cookies. This information can be later retrieved by the website or by any third party. These types of cookies are generally referred to as browser/web/internet cookies.

In general, cookies are used for session management, personalization, and tracking. The validity of a cookie can also be set while it is being created. And cookies’ visibility can be controlled by setting its access level.

Whenever information that’s used across the website for different purposes is required, then the webserver which hosts the web application sends the cookie to the client to make it easier for the subsequent calls.

In general, cookies contain six parameters: the name of the cookie, the value that needs to be stored in the cookie, the expiration date of the cookie, the path to which the cookie is accessible, valid domains for the cookie, and secure connection access.

A practical example of creating and accessing cookies

To understand how to set and retrieve cookies in an ASP.NET MVC application, we are going to create a sample project with ASP.NET Core Web App.

As a first step, create an ASP. Net Core Web App from the predefined project templates provided in the Visual Studio.

Provide a valid name for the solution and choose the .NET 5.0 framework.

Once the solution and project are created, the predefined project template folder structure looks like below.

The code works based on the MVC architecture and the Home Controller consists of three action methods:

  • The Index (the landing page of the website)
  • Privacy (separate page on the website)
  • Error (Page to display error).

Each action present in the controller is mapped to a View within the controller.

Here, we are going to make use of the three action methods to set up the cookie-related information for our understanding. Let's dive deep into it.

As we know, the Index action method gets triggered when the website starts. So we are going to set a cookie in that method. We are also going to set a sample value for the key ‘username’ as a cookie in the index page of the home controller.

public void StoreCookie()

​    {
​      var userNameCookie = HttpContext.Request.Cookies["username"];

​      if (userNameCookie == null)
​      {
​        Response.Cookies.Append("username", "testuser");
​      }
​    }

The above method checks whether the cookie for the ‘username’ is present, if not, sets a value for it. This method needs to be called in the Index action method before it returns the view.

When the application starts, the cookie for ‘username’ will be null and immediately the above method sets the value for it.

This can be verified by calling the Privacy action method, where we are going to check whether the cookie has been set or not. To verify, the below method needs to be called from the Privacy action method before it returns the view.

public void GetCookie()
​    {
​      var userNameCookie = HttpContext.Request.Cookies["username"];
​      Console.WriteLine(userNameCookie);
​    }

On entering the Privacy page, the code has the value for the cookie - ‘username’.

So far, we have seen how to set and retrieve a cookie. To delete a cookie, the below method can be created. And for our understanding, we are going to call this method whenever the error page is called.

public void DeleteCookie()
​    {
​      Response.Cookies.Delete("username");
​    }

Now, after deleting, if the privacy page is called, then the cookie value will not be present. So, it is the responsibility of the developer to clear the cookie at the right moment and make the most of it.

Also, as we saw in the previous section, it is possible to set a few parameters for cookies (expiry, domain, site, etc..,). To set the parameters for cookies, we need to make use of the different cookie options. And below is a sample code on how to set the values and append them with the cookie.

CookieOptions option = new CookieOptions()
​        {
​          Expires = DateTime.Now.AddMinutes(10),
​        };
​        Response.Cookies.Append("username", "testuser", option);

Conclusion

In this post, we have seen what cookies are and how to implement them in an ASP.NET MVC application. By now you would have realized how important it is for website owners. By storing the cookies on the user's browsers, they are able to customize the user experience for them. This improves user satisfaction for these websites. So go ahead and use them in your next application.