1

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?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • You're registering `HttpContextAccessor` but injecting `IHttpContextAccessor`. Shouldn't you use the overload that takes two types (service + implementation)? – Kirk Woll Mar 09 '21 at 21:57
  • Are you sure `accessor` is `null`? I'm asking because you have a line of code `accessor.HttpContext.Features.Get()`. It might be that `HttpContext` is null or `Features` is null. From the other inside, you said disabling prerendering didn't help, so the issue, probably, depends on IIS. The simple application created as `dotnet new blazorserver` with prerendering and `HttpContextAccessor` shows no error, context always is not null. You can deploy such test application on IIS and check, does error appear. – Igor Goyda Mar 09 '21 at 22:12
  • See https://stackoverflow.com/questions/59538318/how-to-use-the-httpcontext-object-in-server-side-blazor-to-retrieve-information/59538319#59538319 – Ben Sampica Mar 10 '21 at 01:14
  • 2
    @Ben Sampica, this is not the proper url to direct him to. This is the proper one: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-5.0#blazor-and-shared-state . Now that he has learned from the official docs that HttpContext is not available in Blazor Server App, he can read my answer... – enet Mar 10 '21 at 01:30
  • 1
    I had same problem.but I have solved it. You can reference : https://stackoverflow.com/questions/59538132/httpcontext-is-null-when-running-web-app-in-iis – Nono.huang Apr 29 '21 at 06:30

0 Answers0