Maui Blazor 中文社区 QQ群:645660665

如何在 Blazor 中使用 cookie 和展示隐私条例横幅

在以下示例中,将显示 cookie 同意横幅以通知您接受 cookie。按照以下步骤在 Blazor 中创建同意 cookie。

  1. Configure 配置HttpContextAccessor和CookiePolicyOptions,创建同意cookie隐私条例横幅

[Program.cs]

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

...
builder.Services.Configure<CookiePolicyOptions>(options =>
{
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.AddHttpContextAccessor();
...

var app = builder.Build();
...
app.UseCookiePolicy();
...

  1. 将 Cookie 同意横幅模板添加到 Shared 文件夹

[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 fade show" role="alert">
        <h4>隐私政策</h4>
<p>我们将根据法律规定,对我们网站收集的个人数据进行保密。我们的公司政策对数据保护和信息安全有着严格规定。 收集和处理个人数据除非您自愿为了特定的目的...</p>
        <button type="button" class="accept-policy close" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString" @onclick="AcceptMessage">
            接受 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 void AcceptMessage()
    {
        // JsInterop call to store the consent cookies.
        JSRuntime.InvokeVoidAsync("CookieFunction.acceptMessage", cookieString);
        showBanner = false;
    }
}
  1. Pages/_Layout.cshtml 文件中添加JavaScript函数来存储cookie

[_Layout.cshtml]

<body>
      . . .
      . . .

      <script>
        window.CookieFunction = {
            acceptMessage: function (cookieString) {
                document.cookie = cookieString;
            }
        };    
   </script>
</body>
  1. MainLayout.razor 文件中添加cookie隐私条例横幅Razor组件

[MainLayout.razor]

<div class="page">
    . . .
    . . .

    <div class="main">
        . . .
        . . .
        <ConsentCookie />

        <div class="content px-4">
            @Body
        </div>
    </div>
</div>
  1. 运行应用程序,将会出现隐私条例横幅和同意按钮

  1. 现在,单击接受 cookie 按钮将 cookie 存储在浏览器中

参考
https://www.syncfusion.com/faq/blazor/tips-and-tricks/how-do-i-set-consent-cookies-in-blazor

项目源码

Github | Gitee

知识共享许可协议

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名AlexChow(包含链接: https://github.com/densen2014 ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系

AlexChow

今日头条 | 博客园 | 知乎 | Gitee | GitHub

posted @ 2022-05-13 23:01  AlexChow  阅读(254)  评论(2编辑  收藏  举报