Search code examples
cookieshttpcontextblazor

How do I access HttpContext in Server-side Blazor?


I need to access HttpContext in a page (.cshtml) and in particular a request and then a cookie. Despite available, HttpContextAccessor always has a null value stored in its HttpContext property.

Any ideas would be much appreciated.

Thanks in advance.

EDIT: the Blazor version I use is: 0.7.0.


Solution

  • Add the following to Blazor.Web.App.Startup.cs:

    services.AddHttpContextAccessor();
    

    You also need this in <component-name>.cshtml

    @using Microsoft.AspNetCore.Http
    @inject IHttpContextAccessor httpContextAccessor
    

    Note: At the time when this answer was written, accessing the HttpContext was done as described above. Since then, Blazor has been under rapid development, and has fundamentally changed. It is definitely deprecated the usage described above, but alas, you can still do the above, which is legitimate and right, if you access the HttpContext from a .cshtml page. This has not changed... Thus the only place from which you can access the HttpContext, without even adding the IHttpContextAccessor to the DI container, is the _Host.cshtml file, which is a Razor Pages file, with the .cshtml extension. When the code in this file is executed, Blazor is still not born, and the execution of this file will be serving the Blazor Server App. Please, see this answer as to how to do it properly...

    Hope this helps...