DEV Community

Dries Deboosere
Dries Deboosere

Posted on • Originally published at driesdeboosere.dev on

How to add cookie consent in ASP.NET 6

Let's configure our Program.cs class by add this configuration:

builder.Services.Configure(options =>
{
    // This lambda determines whether user consent for non-essential 
    // cookies is needed for a given request.
    options.CheckConsentNeeded = context => true;

    options.MinimumSameSitePolicy = SameSiteMode.None;
});
Enter fullscreen mode Exit fullscreen mode

Add following code in your Program class:

app.UseCookiePolicy();
Enter fullscreen mode Exit fullscreen mode

Example:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.Configure(options =>
{
    // This lambda determines whether user consent for non-essential 
    // cookies is needed for a given request.
    options.CheckConsentNeeded = context => true;

    options.MinimumSameSitePolicy = SameSiteMode.None;
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

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

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
Enter fullscreen mode Exit fullscreen mode

Add a new Razor page in the Shared folder with the name: `_CookieConsentPartial.cshtml' and add following code in this new page:

`
@using Microsoft.AspNetCore.Http.Features

@{
var consentFeature = Context.Features.Get();
var showBanner = !consentFeature?.CanTrack ?? false;
var cookieString = consentFeature?.CreateConsentCookie();
}

@if (showBanner)
{

    Use this space to summarize your privacy and cookie use policy. Learn More.

        Accept



    (function () {
        var button = document.querySelector("#cookieConsent button[data-cookie-string]");
        button.addEventListener("click", function (event) {
            document.cookie = button.dataset.cookieString;
        }, false);
    })();
Enter fullscreen mode Exit fullscreen mode

}
`

Now add the partial tag-helper in your `_Layout.cshtml' page:



  @RenderBody()

Enter fullscreen mode Exit fullscreen mode

You can place this partial tag-helper anywhere you want in your HTML code.

If you run your web application you should see something like this:

cookie consent example

If you click Accept then you'll see the cookie message disappear. Refresh your page and you'll see that the message doesn't come back.

Top comments (0)