如何在 Blazor 服务器中设置同意 cookie

Ned*_*ers 8 c# cookies asp.net-identity blazor blazor-server-side

我有一个带有身份的 Blazor 3.1 应用程序,我想在其中实施 cookie 同意横幅。

在经典的 ASP .NET Core 中,有一个很好的 cookie 同意横幅模板。

    @using Microsoft.AspNetCore.Http.Features

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

    @if (showBanner)
    {
        <div class="container">
            <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 class="alert-link" asp-area="" asp-controller="Home" asp-action="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>
        </div>
        <script>
            (function () {
                var button = document.querySelector("#cookieConsent button[data-cookie-string]");
                button.addEventListener("click", function (event) {
                    document.cookie = button.dataset.cookieString;
                }, false);
            })();
        </script>
    }
Run Code Online (Sandbox Code Playgroud)

如果您将此部分放置在布局中,您将拥有一个完美的 cookie 同意横幅。如果配置得当,用户在同意之前甚至无法登录身份框架。

由于 Blazor 不知道 HttpContext,因此此模板不起作用。是否有样板方法,还是我必须自己创建此功能?

小智 12

我昨天刚刚在 Blazor 3.1 应用程序中解决了这个问题!我选择使用 JS Interop,它非常简单。

我的 Web 应用程序有多个前端,包括 MVC、Razor Pages 和 Blazor,因此您可以打开主解决方案文件,然后查看 Blazor 项目:

https://github.com/shahedc/NetLearnerApp

Blazor 项目中需要注意的事项;

  • 我将局部视图实现为剃刀组件

  • 在 Shared 文件夹中查找 /_CookieConsentPartial.razor

  • MainLayout.razor 使用这个 razor 组件

  • _Host.cshtml 文件包括我的 js 互操作文件

  • 在 wwwroot 中查找 netLearnerJsInterop.js

  • js 互操作文件包含 document.cookie 用法

  • razor 组件使用 JSRuntime.InvokeVoidAsync 调用 JS 方法接受 GDPR 同意消息并存储 cookie