Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 714
Alexander Christov Avatar asked Dec 17 '18 14:12

Alexander Christov


People also ask

How do I use HttpContext session in Blazor?

Use(async delegate (HttpContext Context, Func<Task> Next) { //this throwaway session variable will "prime" the Set() method //to allow it to be called after the response has started var TempKey = Guid. NewGuid(). ToString(); //create a random key Context. Session.

How do I access HttpContext in Web API?

ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.

How do I find HttpContext current?

If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically: public Task Invoke(HttpContext context) { // Do something with the current HTTP context... }

How do I get the current URL in Blazor?

Inject NavigationManager in razor. Use Uri from NavigationManager to get the current URL.


2 Answers

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...

like image 194
enet Avatar answered Sep 19 '22 11:09

enet


It depends what you want to access the HttpContext for.

Should you want to access authentication or user info, consider using the AuthenticationStateProvider instead:

@page "/" @using System.Security.Claims @using Microsoft.AspNetCore.Components.Authorization @inject AuthenticationStateProvider AuthenticationStateProvider  <h3>ClaimsPrincipal Data</h3>  <button @onclick="GetClaimsPrincipalData">Get ClaimsPrincipal Data</button>  <p>@_authMessage</p>  @if (_claims.Count() > 0) {     <ul>         @foreach (var claim in _claims)         {             <li>@claim.Type &ndash; @claim.Value</li>         }     </ul> }  <p>@_surnameMessage</p>  @code {     private string _authMessage;     private string _surnameMessage;     private IEnumerable<Claim> _claims = Enumerable.Empty<Claim>();      private async Task GetClaimsPrincipalData()     {         var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();         var user = authState.User;          if (user.Identity.IsAuthenticated)         {             _authMessage = $"{user.Identity.Name} is authenticated.";             _claims = user.Claims;             _surnameMessage =                  $"Surname: {user.FindFirst(c => c.Type == ClaimTypes.Surname)?.Value}";         }         else         {             _authMessage = "The user is NOT authenticated.";         }     } } 
like image 21
Shimmy Weitzhandler Avatar answered Sep 19 '22 11:09

Shimmy Weitzhandler