Home > Back-end >  ASP.NET HttpContext is null on Azure
ASP.NET HttpContext is null on Azure

Time:12-22

I have a ASP.NET Blazor Web App, which is hosted on Azure. Everything works, except one minor thing. I use the IHttpContextAccessor.HttpContext as described in the Documentation.

    public class SessionService : ISessionService
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IUserService userService;

        public SessionService(
            IUserService userService,
            IHttpContextAccessor httpContextAccessor)
        {
            this.userService = userService;
            this.httpContextAccessor = httpContextAccessor;
        }

        public async Task<User> GetUser()
        {
            var userId = this.httpContextAccessor.HttpContext?.Items["userId"]?.ToString();
            
            if (userId == null)
            {
                return null;
            }

            if (!int.TryParse(userId, out var parsedUserId))
            {
                return null;
            }

            return await this.userService.Get(parsedUserId);
        }

        /// <inheritdoc />
        public async Task AuthenticateUser()
        {
            if (this.httpContextAccessor.HttpContext == null)
            {
                return;
            }

            // Authentication Logic
            // ...

            this.httpContextAccessor.HttpContext.Items["userId"] = authenticatedUser.id;
        }
    }

I later call this code similar to this:

var user = await sessionService.GetUser();
if (user == null)
{
   await sessionService.AuthenticateUser();
   user = await sessionService.GetUser();
}

This works on every local machine I've tested so far. It does not matter if I build it in Release or Debug. All of the data gets loaded correctly and I can retrieve the ID of the currently logged in user.

Anyways, if I publish the application to azure, the HttpContext is always null. I have checked the documentation multiple times now and cannot find anything that pushes me in the right direction. Do I need to configure something to specifically use the HttpContext?

CodePudding user response:

You need to inject AuthenticationStateProvider to get info from graph and please don't use IHttpContextAccessor because it has a security issue, you can read more about that in microsoft doc.
How you can use AuthenticationStateProvider:
In blazor page inject AuthenticationStateProvider like this:

[Inject]
public AuthenticationStateProvider AuthenticationState { get; set; }
 
protected override async Task OnInitializedAsync()
{
  var AuthSate = await AuthenticationState.GetAuthenticationStateAsync();
  var user = AuthSate.User;
} 
  • Related