2

In my Blazor Server app I have this code in a component that needs to read cookies from the Request (so I would read them before the render):

[Inject] private IHttpContextAccessor HttpCxAccessor { get; set; }

...

protected override void OnInitialized()
{
    var context = HttpCxAccessor.HttpContext;
    // context is null when on Local IIS

the code works when I run it from VS (IISExpress) but when I publish it on local IIS, the HttpContext is null

buga
  • 852
  • 9
  • 21

1 Answers1

1

You shouldn't use HttpContextAccessor in Blazor Server because the Blazor Server works outside the .NetCore pipeline and basically there is no guarantee that you will have access to the desired amount of HttpContext everywhere for more info you can refer to this issue. However, If you have to use the HttpContext then you have to get the desired value(s) from HttpContext when rendering _Host.cshtml and save it in a variable and use that variable in the form of Cascading Parameters in the components in the rest of the program.

An Example of implementation is here.

Arani
  • 891
  • 7
  • 18
  • Thank You, I actually already tried something similar but couldn't get the value to cascade, it turned out the Property Name is not important I have to use `[CascadingParameter(Name="ParamName")]` – buga Dec 04 '22 at 19:08
  • You're welcome, I am glad that your problem is solved. – Arani Dec 05 '22 at 04:52