7

I can't access Session variables outside controllers, there are over 200 examples where they advise you to add ;

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

services.AddHttpContextAccessor();

and use

public class DummyReference
{
        private IHttpContextAccessor _httpContextAccessor;
        public DummyReference(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
        public void DoSomething()
        {
            // access _httpcontextaccessor to reach sessions variables
        }
}

But, no-one mentions how to call this class from my controller. How can I reach that class?

If changed it to static then I need bypass construct. If I create it I need httpcontextaccessor for construct.

For who wants learn more why I approached like that, I want to write class include methods like encrypt, decrypt database tables RowIDs for masking in VIEW with value+sessionvariable to ensure its not modified.

Also I want DummyReference to be static, that way I can easily reach DummyReference.EncryptValue or DecryptValue.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Mopener
  • 83
  • 1
  • 1
  • 5
  • Possible duplicate of [How to get HttpContext.Current in ASP.NET Core?](https://stackoverflow.com/questions/38571032/how-to-get-httpcontext-current-in-asp-net-core) – Asons Jul 06 '19 at 11:37

4 Answers4

8

Don't use IHttpContextAccessor outside of controllers. Instead, use HttpContextAccessor.

Like this in static classes ;

private static HttpContext _httpContext => new HttpContextAccessor().HttpContext;

Or anywhere else. You still need service of course and the thing we do in the controllers.

heimzza
  • 276
  • 4
  • 12
4

the same happend to me I found the solution putting in my method into the no controller class (where I want to use it)

var HttpContext = _httpContextAccessor.HttpContext;

var vUser =  _httpContextAccessor.HttpContext.Session.GetString("user");
Joshua Robinson
  • 3,399
  • 7
  • 22
2

According to Microsoft docs

Add

builder.Services.AddHttpContextAccessor();

Then

private readonly IHttpContextAccessor _httpContextAccessor;

public UserRepository(IHttpContextAccessor httpContextAccessor) =>
    _httpContextAccessor = httpContextAccessor;
1

That code gets you the current HttpContext. Sessions are slightly different: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2

Robert Perry
  • 1,906
  • 1
  • 14
  • 14