Using cookies in ASP.NET Core

By FoxLearn 1/7/2025 7:18:04 AM   48
A cookie is a small data file stored on a user's computer to hold information about the user. While most browsers store cookies as individual files, Firefox stores them together in one file.

Cookies are structured as key-value pairs, which allow users to read, write, or delete them using the keys.

ASP.NET Core utilizes cookies to manage session state, with the session ID being sent to the client in the cookie with every request.

In ASP.NET Core, cookies can be read from the Request.Cookies collection using a specified key.

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

To set a cookie with an expiration time, the Append method can be used with a CookieOptions object.

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

The CookieOptions class allows you to set additional cookie properties, including the domain, expiration time, path, security policy (HTTPS access), and whether the cookie is restricted to server access only (HttpOnly).

To write a cookie, you can use the Append method of the Response.Cookies collection.

Response.Cookies.Append(somekey, somevalue);

To remove a cookie, you can use the Delete method of the Response.Cookies collection.

Response.Cookies.Delete(somekey);

Access HttpContext in ASP.NET Core

In this section, we will explore how to work with cookie data in ASP.NET Core.

To access the Request object, you'll need to access the HttpContext. This can be done using the IHttpContextAccessor interface, which is implemented by the HttpContextAccessor class.

First, register the IHttpContextAccessor for dependency injection.

For example, how to add a singleton service for HttpContextAccessor in the ConfigureServices method of the Startup class:

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

Next, use dependency injection to obtain a reference to the IHttpContextAccessor instance, which will give you access to HttpContext.

For example, how to access the IHttpContextAccessor in a controller.

public class HomeController : Controller
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public HomeController(IHttpContextAccessor httpContextAccessor)
    {
        this._httpContextAccessor = httpContextAccessor;
    }

    // Write your action methods here
}

You can use the following method in your controller to write cookie data:

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(15);

    _httpContextAccessor.HttpContext.Response.Cookies.Append(key, value, options);
    return View("WriteCookie");
}

After successfully writing the cookie data, you can use the following method to read the cookie data in your controller:

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

To verify if the cookie has been written correctly, you can check the cookie cache in your web browser.