ASP.NET Tutorial : Using Cookies in ASP.NET Core

HTTP Cookie is some piece of data that is stored in the user’s browser. HTTP cookies play a vital role in the software world. We can store users’ related information in cookies and there are many other usages. In asp.net core working with cookies is made easy. I’ve written a couple of abstraction layers on top of the HTTP cookie object. Cookies are key-value pair collections where we can read, write, and delete using a key. In ASP.NET, we can access cookies using httpcontext.current but in ASP.NET Core, there is no HTTP context.currently. In ASP.NET Core, everything is decoupled and modular.

Httpcontext is accessible from the Request object and the IHttpContextAccessor interface which is under the “Microsoft.AspNetCore.Http” namespace and this is available anywhere in the application.Update: I have written a wrapper on top of HTTP Cookie which helps you to ease of use and secure the cookie data. CookieManager is an ASPNET Core Abstraction layer on top of the cookie.

Reading Cookie
HttpCookie is accessible from Request. Cookies. Given below is the sample code.

// Read cookie from IHttpContextAccessor
string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["key"];

// Read cookie from Request object
string cookieValueFromReq = Request.Cookies["Key"];

Writing cookie
Here is the code snippet to write cookies. Set method to write cookies. CookieOption is available to extend the cookie behavior.

/// <summary>
/// Set the cookie
/// </summary>
/// <param name="key">Key (unique identifier)</param>
/// <param name="value">Value to store in cookie object</param>
/// <param name="expireTime">Expiration time in minutes</param>
public void Set(string key, string value, int? expireTime)
{
    CookieOptions option = new CookieOptions();

    if (expireTime.HasValue)
    {
        option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
    }
    else
    {
        option.Expires = DateTime.Now.AddMilliseconds(10);
    }

    Response.Cookies.Append(key, value, option);
}

Remove Cookie

Delete the cookie by key name.

/// <summary>
/// Delete the cookie by key
/// </summary>
/// <param name="key">Key (identifier of the cookie to delete)</param>
public void Remove(string key)
{
    Response.Cookies.Delete(key);
}

CookieOptions
It extends the cookie behavior in the browser.

Options

  1. Domain: The domain you want to associate with a cookie
  2. Path: Cookie Path
  3. Expires: The expiration date and time of the cookie
  4. HttpOnly: Gets or sets a value that indicates whether a cookie is accessible by client-side script or not.
  5. Secure: Transmit the cookie using Secure Sockets Layer (SSL) that is, over HTTPS only.

Here is the complete code example to read, write, and delete the cookie.

public class HomeController : Controller
{
    private readonly IHttpContextAccessor _httpContextAccessor;

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

    public IActionResult Index()
    {
        // Read cookie from IHttpContextAccessor
        string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["key"];

        // Read cookie from Request object
        string cookieValueFromReq = Request.Cookies["Key"];

        // Set the key value in Cookie
        Set("key", "Hello from cookie", 10);

        // Delete the cookie object
        Remove("Key");

        return View();
    }

    /// <summary>
    /// Get the cookie
    /// </summary>
    /// <param name="key">Key</param>
    /// <returns>string value</returns>
    public string Get(string key)
    {
        return Request.Cookies[key];
    }
    /// <summary>
    /// Set the cookie
    /// </summary>
    /// <param name="key">Key (unique identifier)</param>
    /// <param name="value">Value to store in cookie object</param>
    /// <param name="expireTime">Expiration time</param>
    public void Set(string key, string value, int? expireTime)
    {
        CookieOptions option = new CookieOptions();

        if (expireTime.HasValue)
            option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
        else
            option.Expires = DateTime.Now.AddMilliseconds(10);

        Response.Cookies.Append(key, value, option);
    }

    /// <summary>
    /// Delete the key
    /// </summary>
    /// <param name="key">Key</param>
    public void Remove(string key)
    {
        Response.Cookies.Delete(key);
    }
}

I hope you learned how to work with cookies in ASP.NET Core. I have shown you an example of reading, writing, and removing cookie objects.

Best and Most Recommended ASP.NET Core 8.0.4 Hosting

Fortunately, there are a number of dependable and recommended web hosts available that can help you gain control of your website’s performance and improve your ASP.NET Core 8.0.4 web ranking. HostForLIFEASP.NET is highly recommended. In Europe, HostForLIFEASP.NET is the most popular option for first-time web hosts searching for an affordable plan.

Their standard price begins at only € 3.49 per month. Customers are permitted to choose quarterly and annual plans based on their preferences. HostForLIFEASP.NET guarantees “No Hidden Fees” and an industry-leading ’30 Days Cash Back’ policy. Customers who terminate their service within the first thirty days are eligible for a full refund.

By providing reseller hosting accounts, HostForLIFEASP.NET also gives its consumers the chance to generate income. You can purchase their reseller hosting account, host an unlimited number of websites on it, and even sell some of your hosting space to others. This is one of the most effective methods for making money online. They will take care of all your customers’ hosting needs, so you do not need to fret about hosting-related matters.