クッキー同意を加える方法.ネットコア5.0


既存のASPでクッキー同意を加える方法を学んでください.NETコア3.1または5.0 Webアプリケーション.
設定しましょうStartup.cs この設定を使用してステートメントを使用してクラスを指定します.
usingステートメントを追加します.
using Microsoft.AspNetCore.Http;
次のコードを追加しますConfigureServices あなたの方法Startup クラス
// Sets the display of the Cookie Consent banner (/Pages/Shared/_CookieConsentPartial.cshtml).
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
services.Configure<CookiePolicyOptions>(options => {
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.Strict;
});
次のコードを追加しますConfigure あなたの方法Startup クラス
app.UseCookiePolicy();
例:
using Microsoft.AspNetCore.Http;

public void ConfigureServices(IServiceCollection services)
{
    // Sets the display of the Cookie Consent banner (/Pages/Shared/_CookieConsentPartial.cshtml).
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
    services.Configure<CookiePolicyOptions>(options => {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.Strict;
    });

    services.AddRouting(options => options.LowercaseUrls = true);
    services.AddRazorPages().AddRazorRuntimeCompilation();
    services.AddHttpContextAccessor();

    services.AddScoped<IProjectService, ProjectService>();
    services.AddScoped<IBlogService, BlogService>();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseCookiePolicy();
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}
新しいカミソリページをShared 名前を持つフォルダ:' Range cookieconsentpartial.次のコードを追加します.
@using Microsoft.AspNetCore.Http.Features

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

@if (showBanner)
{
    <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 asp-page="/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>
    <script>
        (function () {
            var button = document.querySelector("#cookieConsent button[data-cookie-string]");
            button.addEventListener("click", function (event) {
                document.cookie = button.dataset.cookieString;
                var cookieContainer = document.querySelector("#cookieConsent");
                cookieContainer.remove();
            }, false);
        })();
    </script>
}
今すぐ追加partial あなたの'安値レイアウトのタグヘルパー.ページを見る
<div class="container">
  <main role="main" class="pb-3">@RenderBody()</main>
  <partial name="_CookieConsentPartial" />
</div>
この部分タグヘルパーをHTMLコードで任意の場所に配置できます.
Webアプリケーションを実行する場合は、次のように表示されます.

をクリックすると、クッキーのメッセージが表示されなくなります.ページをリフレッシュして、メッセージが戻ってこないことがわかります.