top of page
Writer's pictureThe Tech Platform

Cookies in ASP.NET Core

Updated: Jun 14, 2023


cookies in ASP.NET Core

In web development, cookies play a crucial role in maintaining the session state and improving the browsing experience for users. Cookies are small pieces of data that websites store within web browsers and retrieve later. Cookies in ASP.NET Core are used to identify specific users and manage session information. This article will guide you through the process of working with cookies in ASP.NET Core, covering how to write, read, and delete cookies.


Types of Cookies: There are two primary types of cookies:

  1. Session Cookies: Session cookies are temporary cookies that are stored on the user's computer for the duration of their visit to a website. They are typically used to maintain session state and are destroyed when the user closes their browser or navigates away from the web page.

  2. Persistent Cookies: Persistent cookies are long-term cookies that can be stored across multiple sessions. They retain information such as login credentials or user preferences, allowing users to have a personalized experience when they revisit a website.


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


1. Writing a Cookie:

To write a cookie in ASP.NET Core, you need to execute the "WriteCookie" action method. In this method, you first set the expiry date of the cookie using the CookieOptions class. Then, you add the cookie to the Response.Cookies collection using the Append method, which takes the cookie name, value, and a CookieOptions object as parameters.

CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Append("somekey", "somevalue", options);

2. Reading a Cookie:

To read a cookie, you need to execute the "ReadCookie" action method. Within this method, you retrieve the cookie value from the Request.Cookies collection using its key. The retrieved value is then set in the TempData object, which can be later displayed using a JavaScript alert message box.

string cookieValue = Request.Cookies["Key"];
TempData["CookieValue"] = cookieValue;

If you want to specify the expiration time for the cookie, you can use the overloaded version of the Append method, as shown below:

CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Append("key", "value", options);

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

  • Domain: Specifies the domain associated with the cookie.

  • Expiration time: Determines the cookie's expiration time.

  • Path: Defines the path for which the cookie is valid.

  • Security policy: Specifies if the cookie should be accessible only over HTTPS.

  • HttpOnly: Indicates if the cookie is available only to the server.


3. Deleting a Cookie:

To delete a cookie, you need to execute the "DeleteCookie" action method. Within this method, you can remove the cookie from the Request.Cookies collection using the Delete method.

Response.Cookies.Delete("somekey");

Working with Cookies in ASP.NET Core: A Practical Example

The below code is an example of an ASP.NET Core controller and corresponding view that demonstrates how to work with cookies in a web application.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

public class HomeController : Controller
{
    private readonly IHttpContextAccessor _accessor;

    public HomeController(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }

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

    [HttpPost]
    public IActionResult WriteCookie(string name)
    {
        // Set the expiry date of the cookie.
        CookieOptions options = new CookieOptions();
        options.Expires = DateTime.Now.AddDays(30);

        // Create a cookie with a suitable key and add it to the browser.
        Response.Cookies.Append("Name", name, options);

        return RedirectToAction("Index");
    }

    [HttpPost]
    public IActionResult ReadCookie()
    {
        // Fetch the cookie value using its key.string name = _accessor.HttpContext.Request.Cookies["Name"];

        TempData["Message"] = name != null ? name : "undefined";

        return RedirectToAction("Index");
    }

    [HttpPost]
    public IActionResult DeleteCookie()
    {
        // Delete the cookie from the browser.
        Response.Cookies.Delete("Name");

        return RedirectToAction("Index");
    }
}

CSS Code

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
    </head>
    <body>
    <form method="post" asp-controller="Home"><span>Name: </span><input type="text" id="txtName" name="name" /><br/><br/>
    <input type="submit" id="btnWrite" formaction="@Url.Action("WriteCookie")" value="Write Cookie" />
    <input type="submit" id="btnRead" formaction="@Url.Action("ReadCookie")" value="Read Cookie" />
    <input type="submit" id="btnDelete" formaction="@Url.Action("DeleteCookie")" value="Remove Cookie" />
</form>
    
    @if (TempData["Message"] != null)
    {
        <script type="text/javascript">window.onload = function () 
        {
                alert('@TempData["Message"]');
            };
        </script>
    }
    </body>
</html>

Explanation:

  • The HomeController class inherits from the Controller class provided by ASP.NET Core.

  • The IHttpContextAccessor interface is injected into the controller's constructor via dependency injection. It allows access to the current HttpContext.

  • The Index action method returns the main view for the home page.

  • The [HttpPost] attribute is used to indicate that the following action methods should be triggered by HTTP POST requests.

  • The WriteCookie action method sets the expiry date for the cookie and then creates a cookie with a key-value pair. It appends the cookie to the browser's response. The provided name parameter is used as the cookie value.

  • The ReadCookie action method retrieves the value of the "Name" cookie from the current request's cookies collection. The value is stored in the TempData object, which is later accessed in the view to display a message.

  • The DeleteCookie action method deletes the "Name" cookie from the browser's response.

  • The corresponding view code (CSS and HTML) displays a form with a text input for entering a name. Three buttons are provided to write, read, and delete the cookie. When the cookie is read or deleted, a JavaScript alert is displayed with the retrieved cookie value or a default message if the cookie value is null.

Working with cookies in ASP.NET Core is straightforward and allows developers to maintain session state and provide a personalized browsing experience. By utilizing the provided example, you can effectively write, read, and delete cookies in your ASP.NET Core applications. Understanding the fundamentals of cookie management empowers developers to enhance user interactions and deliver dynamic web applications.


Conclusion

Cookies are essential for maintaining session state and providing a personalized browsing experience in web applications. In ASP.NET Core, you can easily work with cookies by writing, reading, and deleting them. By understanding how to interact with cookies, you can enhance the functionality and user experience of your ASP.NET Core applications.


Comments


bottom of page