5

I'm using HttpContext from IHttpContextAccessor in a dotnet core 3.1 web app in a couple of scenarios. It is always set as I would expect.

However, HttpContext is always null when injecting IHttpContextAccessor into a razor component.

@inject IHttpContextAccessor HttpContextAccessor

<div>...</div>

@code {
    protected override async Task OnInitializedAsync()
    {
        // here, HttpContextAccessor.HttpContext == null
    }

    public string GetSomeInfo()
    {
        // here, HttpContextAccessor.HttpContext == null
    }
}

I have added IHttpContextAccessor in Startup.cs/ConfigureServices() like so

services.AddHttpContextAccessor();

Why is HttpContext null here?

Stephan
  • 1,791
  • 1
  • 27
  • 51
  • In server side blazor you should use `AuthenticationStateProvider` instead of `HttpContext`. https://learn.microsoft.com/en-us/aspnet/core/security/blazor/?view=aspnetcore-3.1&tabs=visual-studio#authenticationstateprovider-service – Pascal R. Jan 24 '20 at 07:28
  • Did you check the answers here https://stackoverflow.com/q/53817373/2224701 ? – Vojtěch Dohnal Jan 24 '20 at 08:54

1 Answers1

2

I usually add a parameter to razor component. Suppose you stored a string in HttpContext.State and want to display it in a razor component:

Counter.razor:

<span>Application Name: @AppTitle</span>

@code {
    [Parameter]
    public HttpContext MyContext { get; set; }

    public string AppTitle => MyContext.State.GetString("APP_KEY");
}

The component in your razor page:

<component type="typeof(Counter)" render-mode="Static" param-MyContext="@HttpContext" />
Federico
  • 21
  • 2