(C# ASP.NET Core) Reading, Writing and Deleting Cookies in ASP.NET Core

We start this walkthrough with a small introduction to the concept of a cookie, and then we explain the various ASP.NET Core snippets to (a) create a cookie, (b) read a cookie and (c) delete a cookie. And lastly, we create a fully functional application for creating and deleting cookies. You can run the application to see the whole concept in action! We strongly recommend that you watch the linked video for finer details.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Objective of this Tutorial

We shall write an ASP.NET Core application that will (a) have a button to create a cookie called "_name" and store some text in it (b) a button to delete the above cookie and (c) this form will also display the contents of the cookie.

Brief Concept of a Cookie

ASP.NET Core has functions that can request the browser to create a cookie of some name, some expiry date and some content [4kb], and the browser stores it on the user's machine.

When the browser makes a next request to the same website, then it sends all the active [non-expired] cookies as name-value strings to the ASP.NET Core application. However, there are various finer security considerations that are beyond the scope of this article. Please refer Mozilla website documentation for details.

A most common use of cookies is the "Remember Me" feature on login forms.

Video Explanation with a Working Example

Please watch the following youtube video:

How to Write a Cookie
(full code given towards the end)

The following code is used to request the browser to write a cookie for you.

// cookie options 
CookieOptions op = new CookieOptions();

// absolute expiry date 
op.Expires = . . . date time

// . . . more options 

// a cookie called "_name" is created 
// the text it holds is "hello, cookie!" 
Response.Cookies.Append("_name", "hello, cookie!", op);

How to Read a Cookie
(full code given towards the end)

The best way is to use the TryGetValue method to read a cookie.

// reads the contents of a cookie called "_name" 
// the function returns false if no cookie sent by the 
// browser 
Request.Cookies.TryGetValue("_name", out string strVal)

How to Delete a Cookie
(full code given towards the end)

A cookie can be deleted by using the Delete method as below:

// requests the browser to remove 
// a cookie called "_name" 
Response.Cookies.Delete("_name");

Step 1 of 3: Configure the Startup Class
(see the linked video for details)

You need to make two additions to the startup class:

Addition 1 (Startup > ConfigureServices): Add cookie policy global options to the ConfigureServices method. The code below is commented appropriately.

Addition 2 (Startup > Configure): Add the middleware component called UseCookiePolicy to the request pipeline in the Configure method. The code below is commented appropriately.

// Startup.cs file 
using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.CookiePolicy;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

namespace MyCookieProject
{

  public class Startup
  {

    public void ConfigureServices(IServiceCollection services)
    {

      services.AddRazorPages();

      // ----------Addition 1------ 
      services.Configure<CookiePolicyOptions>(options =>
      {

        // prevent access from javascript 
        options.HttpOnly = HttpOnlyPolicy.Always;

        // If the URI that provides the cookie is HTTPS, 
        // cookie will be sent ONLY for HTTPS requests 
        // (refer mozilla docs for details) 
        options.Secure = CookieSecurePolicy.SameAsRequest;

        // refer "SameSite cookies" on mozilla website 
        options.MinimumSameSitePolicy = SameSiteMode.None;

      });

    }

    // Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      if (env.IsDevelopment())
      {

        app.UseDeveloperExceptionPage();

      }

      app.UseRouting();

      // ----------Addition 2------ 
      // add the CookiePolicy middleware 
      app.UseCookiePolicy();

      app.UseEndpoints(endpoints =>
      {

        endpoints.MapRazorPages();

      });

    }

  }

}

Step 2 of 3: Complete the Index Razor Page
(see the linked video for details)

The following is the razor page with anchor link buttons for creating and deleting a cookie.

@page 

@model MyCookieProject.Pages.IndexModel

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<a asp-page-handler="WriteCookie" asp-page="./Index">
  Set Cookie
</a>

<hr/>

<a asp-page-handler="DeleteCookie" asp-page="./Index">Delete Cookie</a>

@if (!String.IsNullOrEmpty(Model.CookieValue))
{
  <h3>
    Cookie = @Model.CookieValue
  </h3>
}

Step 3 of 3: Complete the IndexModel Class
(see the linked video for details)

The WriteCookie and DeleteCookie handlers can now be completed in the IndexModel class as explained below:

using System;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace MyCookieProject.Pages
{

  public class IndexModel : PageModel
  {

    internal const String CK_KEY_NAME = "_name";


    // handler for write cookie button 
    public IActionResult OnGetWriteCookie()
    {

      CookieOptions op = new CookieOptions();

      // send to the current host, excluding subdomains 
      op.Domain = null;

      // OR to send to domain as well as subdomains 
      // op.Domain = "azurewebsites.net"; 

      // absolute expiry date 
      op.Expires = new DateTime(2021, 02, 01);

      // max has precedence over expires 
      op.MaxAge = TimeSpan.FromDays(365);

      // Add a new cookie and value 
      Response.Cookies.Append(CK_KEY_NAME, "hello, cookie!", op);

      return RedirectToPage();

    }


    // handler for delete cookie 
    public IActionResult OnGetDeleteCookie()
    {

      Response.Cookies.Delete(CK_KEY_NAME);

      return RedirectToPage();

    }

    // stores the contents of our cookie 
    // this property is displayed in the razor page 
    public String CookieValue { get; set; }

    // handle the get request 
    public void OnGet()
    {

      // read the cookie 
      CookieValue =
      Request.Cookies.TryGetValue(CK_KEY_NAME, out string strVal)
      ? strVal : null;

    }

  }

}


This Blog Post/Article "(C# ASP.NET Core) Reading, Writing and Deleting Cookies in ASP.NET Core" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.