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

标签 c# cookies asp.net-identity blazor blazor-server-side

我有一个带有 Identity 的 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>
    }

如果您将此部分放置在布局中,您就拥有了一个完美的工作 cookie 同意横幅。如果配置正确,用户甚至无法登录身份框架,除非他们同意。

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

最佳答案

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

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

https://github.com/shahedc/NetLearnerApp

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

  • 我将部分 View 实现为 Razor 组件

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

  • MainLayout.razor 使用此 razor 组件

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

  • 在 wwwroot 中查找 netLearnerJsInterop.js

  • js Interop 文件包含 document.cookie 用法

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

关于c# - 如何在 Blazor 服务器中设置同意 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59529950/

相关文章:

c# - 使用 Visual Studio 和 NUnit 连接到 localdb

c# - 在 UI 线程上下文中执行代码的正确方法?

cookies - 使用访问或 ID token / token 交换建立 SSO/设置 cookie

asp.net-mvc - 尝试将 asp.net 标识表移至我的数据库

c# - JSON.NET 部分更新 Rest API 客户端

c# - C# 中的 LFU 缓存?

php - 未设置 Cookie 但数据库已更改

ajax - 可以在 AJAX 请求中发送 header 吗?

c# - ASP.Net Core 2.1 注册自定义 ClaimsPrincipal

.net-core - 从 .NET 控制台应用程序登录到 Azure 管理 API