(C# ASP.NET Core) Cookie Consent Banner with ITrackingConsentFeature

This is a walkthrough on how to obtain user consent for usage of cookies on an asp.net core website. This project uses the ITrackingConsentFeature interface to determine if the user has already given his consent, and also to obtain the correct cookie string as per the http format. The readymade functions of this interface make it extremely easy for a developer to obtain a user's consent.

Categories | About |     |  

Parveen,

Objective of this Tutorial
(see the linked video for details)

A consent banner is shown to a visitor if he has not yet given his acceptance to the use of cookies. The banner consists of a custom message, and a button for acceptance.

As soon as the user clicks the button, his acceptance is recorded, and the banner is hidden away.

How it Works

ASP.NET Core provides a service called ITrackingConsentFeature. The instance of this feature is first obtained on a razor page (see the code below).

ITrackingConsentFeature has a property called CanTrack that returns true if the user has already given his consent. So this property can be used to decide if the consent banner has to be shown or not.

The CanTrack property, probably, internally checks for the existence of a cookie on the user's machine.

When the user clicks the consent button, a javascript function is wired to create the consent cookie. The exact string of the consent cookie is obtained by calling the method CreateConsentCookie() of the interface ITrackingConsentFeature.

Video Explanation with a Working Example

Please watch the following youtube video:

Step 1 of 2: Configure the Startup class

Addition 1 (ConfigureServices): first add a line to the ConfigureServices method so that ASP.NET Core can provide you ITrackingConsentFeature for managing cookie consent.

Addition 2 (Configure): next add a line to the Configure method to add UseCookiePolicy middleware to the pipeline.

This is the completed code

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

using Microsoft.AspNetCore.Hosting;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

namespace MyDlgCookieAcceptance
{

  public class Startup
  {

    public void ConfigureServices(IServiceCollection services)
    {

      // add support for razor pages 
      services.AddRazorPages();

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

        // if consent policies should be evaluated 
        options.CheckConsentNeeded = (context => true);

      });

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      if (env.IsDevelopment())
      {

        app.UseDeveloperExceptionPage();

      }

      app.UseRouting();

      // Addition 2 - use cookie policy 
      app.UseCookiePolicy();

      app.UseEndpoints(endpoints =>
      {

        endpoints.MapRazorPages();

      });

    }

  }

}

Step 2 of 2: The Index.cshtml Razor Page
(see the linked video for details)

The following code is for the razor page on which the consent banner has to be shown.


// Index.cshtml file 
// no change is to be made 
// in the backing class Index.cshtml.cs 

@page

@model MyDlgCookieAcceptance.Pages.IndexModel

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@using Microsoft.AspNetCore.Http.Features

@{
  // ITrackingConsentFeature - Used to grant user consent 
  var consentFeature = HttpContext.Features.Get<ITrackingConsentFeature>();

  // CanTrack - indicates if consent has been given 
  var showBanner = !(consentFeature?.CanTrack ?? false);

  // Creates a consent cookie for use 
  // when granting consent from a javascript client. 
  var cookieString = consentFeature?.CreateConsentCookie();
}

@if (showBanner)
{
  <div id="ck" style="border:2px solid black;padding:12px;">

    <span>This site uses cookies</span>

    <button>Accept</button>

  </div>

  <script type="text/javascript">

    (function () {

      // query the consent button 
      var button = document.querySelector("#ck button");

      // add a clickevent handler 
      button.addEventListener("click", function (evt) {

        // create the cookie 
        document.cookie = "@cookieString";

        // hide the dialog 
        ck.style.display = "none";

      }, false);

    })();

  </script>
}

<h1>Welcome to this site!</h1>




This Blog Post/Article "(C# ASP.NET Core) Cookie Consent Banner with ITrackingConsentFeature" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.