I need to add cookie consent to a blazor server-side app. I created a component with the following:
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Http.Features
@inject IHttpContextAccessor accessor
@inject IJSRuntime jsRuntime
here cookie consent text...
@code {
private ITrackingConsentFeature consentFeature;
private bool showBanner;
private string cookieString;
protected override void OnInitialized()
{
consentFeature = accessor.HttpContext.Features.Get<ITrackingConsentFeature>();
showBanner = !consentFeature?.CanTrack ?? false;
cookieString = consentFeature?.CreateConsentCookie();
}
private void AcceptMessage()
{
jsRuntime.InvokeVoidAsync("jsFunctions.acceptMessage", cookieString);
showBanner = false;
}
}
And the following in Startup.cs
:
services.AddHttpContextAccessor();
services.AddScoped<HttpContextAccessor>();
The app works as expected in development mode (no prerendering), but the app fails when deploying in IIS (server prerendered), and a null exception is thrown when trying to access accessor
. Turning off prerendering doesn't help.
How can I get the above to work?