-3

Exception error occurs on this line

_httpContextAccessor.HttpContext.Session.SetString(key, value);

Exception error

System.NullReferenceException: 'Object reference not set to an instance of an object.'  
Microsoft.AspNetCore.Http.IHttpContextAccessor.HttpContext.get returned null.

Code

public class MessageRepository : IMessageRepository
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MessageRepository (IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    //Stores the message in session to pass to another blazor component
    public void SetMessage(string key, string value)
    {
        _httpContextAccessor.HttpContext.Session.SetString(key, value);
    }
}

Reference: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-3.1

001
  • 55,049
  • 82
  • 210
  • 324

1 Answers1

2

Did you read the page you linked...

Additionally, again for security reasons, you must not use IHttpContextAccessor within Blazor apps. Blazor apps run outside of the context of the ASP.NET Core pipeline. The HttpContext isn't guaranteed to be available within the IHttpContextAccessor, nor is it guaranteed to be holding the context that started the Blazor app.

Milney
  • 5,876
  • 2
  • 16
  • 29
  • I recently ran into this, it appears that it is often best to use the AuthenticationStateProvider. – Retic Aug 30 '20 at 15:13