Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Httpcontext outside controller in .net core

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.

like image 212
Mopener Avatar asked May 12 '26 02:05

Mopener


1 Answers

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.

like image 151
heimzza Avatar answered May 13 '26 19:05

heimzza