Learn how to add a cookie consent in an existing ASP.NET Core 3.1 or 5.0 web application.
Let's configure our Startup.cs
class by add this configuration and using statement.
Add the using statement:
using Microsoft.AspNetCore.Http;
Add following code in the ConfigureServices
method of your Startup
class:
// Sets the display of the Cookie Consent banner (/Pages/Shared/_CookieConsentPartial.cshtml). // This lambda determines whether user consent for non-essential cookies is needed for a given request. services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.Strict; });
Add following code in the Configure
method of your Startup
class:
app.UseCookiePolicy();
Example:
using Microsoft.AspNetCore.Http; public void ConfigureServices(IServiceCollection services) { // Sets the display of the Cookie Consent banner (/Pages/Shared/_CookieConsentPartial.cshtml). // This lambda determines whether user consent for non-essential cookies is needed for a given request. services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.Strict; }); services.AddRouting(options => options.LowercaseUrls = true); services.AddRazorPages().AddRazorRuntimeCompilation(); services.AddHttpContextAccessor(); services.AddScoped<IProjectService, ProjectService>(); services.AddScoped<IBlogService, BlogService>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseCookiePolicy(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); }
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<ITrackingConsentFeature>(); var showBanner = !consentFeature?.CanTrack ?? false; var cookieString = consentFeature?.CreateConsentCookie(); } @if (showBanner) { <div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert"> Use this space to summarize your privacy and cookie use policy. <a asp-page="/Privacy">Learn More</a>. <button type="button" class="accept-policy close" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString"> <span aria-hidden="true">Accept</span> </button> </div> <script> (function () { var button = document.querySelector("#cookieConsent button[data-cookie-string]"); button.addEventListener("click", function (event) { document.cookie = button.dataset.cookieString; var cookieContainer = document.querySelector("#cookieConsent"); cookieContainer.remove(); }, false); })(); </script> }
Now add the partial
tag-helper in your '_Layout.cshtml' page:
<div class="container"> <main role="main" class="pb-3">@RenderBody()</main> <partial name="_CookieConsentPartial" /> </div>
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:
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)