How do I add consent cookie component in Blazor?

Views: 1646
Comments: 3
Like/Unlike: 1
Posted On: 03-Jan-2024 22:57 

Share:   fb twitter linkedin
Smith
2890 Points
78 Posts


We can add consent cookie banner using blazor component in .net 8.0. In this article we will see example to add consent cookie footer with accept button.

Follow the below steps to create a consent cookie in Blazor.

  1. Configure the HttpContextAccessor and add CookiePolicyOptions to the Program.cs or startup.cs file to create a consent cookie.
    [Program.cs]
    builder.Services.Configure<CookiePolicyOptions>(options => 
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
    builder.Services.AddHttpContextAccessor();
    var app = builder.Build();
    app.UseCookiePolicy();

    [Startup.cs]
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
            options.ConsentCookie = new CookieBuilder()
            {
                Name = "myconsent"
            };
        });
        services.AddHttpContextAccessor();
    }
  2. Now, add the Cookie consent banner template as a Razor component under the Shared folder.
    [ConsentCookie.razor]
    @using Microsoft.AspNetCore.Http.Features
    @using Microsoft.AspNetCore.Http

    @inject IHttpContextAccessor Http
    @inject IJSRuntime JSRuntime


    @if (showBanner)
    {
        <div id="cookieConsent" class="alert alert-info alert-dismissible">
        <h4><b>We use cookies</b></h4>
            Cookies help us deliver the best experience on our website. By using our website, you agree to the use of our cookie policy.
            <button type="button" class="accept-policy close" aria-label="Close" data-cookie-string="@cookieString" @onclick="AcceptMessage">
                Accept Cookie
            </button>
        </div>
    }
    @code {
        ITrackingConsentFeature consentFeature;
        bool showBanner;
        string cookieString;

        protected override void OnInitialized()
        {
            consentFeature = Http.HttpContext.Features.Get<ITrackingConsentFeature>();
            showBanner = !consentFeature?.CanTrack ?? false;
            cookieString = consentFeature?.CreateConsentCookie();
        }

       private async Task AcceptMessage()
       {
        // JsInterop call to store the consent cookies.
        await JSRuntime.InvokeVoidAsync("JsFunction.acceptCookieMessage", cookieString).ConfigureAwait(false);
       }
    }
  3. Add the JavaScript function in the app.razor/_Layout.cshtml/_Host.cshtml/index.cshtml file to store the cookie.
    [_Layout.cshtml/_Host.cshtml/index.cshtml/app.razor]
    <body>
        <script>
            window.JsFunction = {
                acceptCookieMessage: function (cookieString) {
                    document.cookie = cookieString;
                }
            };  
       </script>
    </body>
  4. Add the cookie consent banner Razor component in the MainLayout.razor file.
    [MainLayout.razor]
     <article class="content px-4"> 
        @Body
    </article>
    <div class="top-row px-4">
       <ConsentCookie />
    </div>
  5. Run the application, and you will see the consent cookie banner.
  6. Now, click the Accept cookie button to store the cookie in the browser.


3 Comments

Great example! It's working fine with chrome. But for Edge, always showing popup if opening new browser instance.


dev3
17-Jan-2024 at 04:51

It seems, we require persistent cookie. For this use follwoing expire option as follow:


services.Configure<CookiePolicyOptions>(options =>
{
options.ConsentCookie = new CookieBuilder()
{
Expiration = TimeSpan.FromDays(366)
};
});

beginer
17-Jan-2024 at 04:56

Thanks for quick response. Great! works for me.


dev3
17-Jan-2024 at 05:19
 Log In to Chat