Tuesday, August 1, 2023

ASP.NET Core - Cookie Consent using ITrackingConsentFeature in Razor page

As we know that configuration done in Startup class is global in the app, we configure for cookie consent in the Startup class. 
Step1. To create cookie consent in .NET Core, we must configure the service for CookiePolicyOptions in ConfigureServices method of Startup class. This option is to check if consent policy should be evaluated on the request.
Step2. Add UseCookiePolicy middleware after UseRouting middleware in the Startup class.
Remaining steps are explained in the project.

Project
  • Open the Visual Studio. 
  • Create web project using ASP.NET Core Empty template.
  • Project name: CookieConsent
  • Solution name: CookieConsent
  • .NET Core version: 5.0
  • Add the AddRazorPages() into the ConfigureServices in Startup class.
  • Configure for CookiePolicyOptions in ConfigureServices as given in the code below. 
  • Use MapRazorPages() as terminal middleware in Startup class.
  • Use UseCookiePolicy() after UseRouting middleware in Startup class.
Look at the below updated code in Startup class.
Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace CookieConsent
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.Configure<CookiePolicyOptions>(op =>
            {
                //Checks if consent policies should be evaluated on this request.
                op.CheckConsentNeeded = context => true;    
            });
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCookiePolicy();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}
Add a new folder and rename it Pages. Add a Razor Page in Pages folder and name it Index. Two files are generated which are Index.cshtml and Index.cshtml.cs. Update the Index.cshtml. The consent cookie is created by client using JavaScript. We pass the consent string sent by server to document.cookie.This single line code of JavaScript is able to create cookie but the cookie string must be valid. If you want to see the consent string value then you can pass it to ViewData and can display on the razor page. By default, the expiry is 1 year after the cookie creation date. Note that model class is not needed in this project. We can delete content of that page.

Index.cshtml
@page
@using Microsoft.AspNetCore.Http.Features;

@{
    var TrackingConsentFeature = HttpContext.Features.Get<ITrackingConsentFeature>();
    var IsSuccess = TrackingConsentFeature?.CanTrack ?? false;
    string ConsentCookieString = TrackingConsentFeature?.CreateConsentCookie();
}

@if (!IsSuccess)
{
    <div id="banner1" style="background-color:lightyellow;margin:auto;border:solid green 3px;padding:10px;">
        This site uses cookies. Please click Accept button.
        <button id="accept">Accept</button>
    </div>
    <script type="text/javascript">
        (function () {
            var anchr = document.getElementById('accept');

            anchr.addEventListener("click", function () {
                // create cookie and store consent cookie data
                document.cookie = "@ConsentCookieString";
                banner1.style.display = "none";
            });

        })()
    </script>
}
<h1>Learn ITrackingConsentFeature in .NET Core</h1>
Run the application. We get the consent banner.
Click the Accept button. The cookie will be saved in the browser.

No comments:

Post a Comment

Hot Topics