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;
});
Add following code in your Program
class:
app.UseCookiePolicy();
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();
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);
})();
}
`
Now add the partial
tag-helper in your `_Layout.cshtml' page:
@RenderBody()
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)