Search code examples
c#asp.net-coreasp.net-identity-3

Wrong HttpContext in Policy


We use a custom Policy to check some database requirement (a token persisted in database), and I need session informations so I injected IHttpContextAccessor to use HttpContext.Session.

public TokenValidHandler(IHttpContextAccessor contextAccessor)
{
     _httpContext = contextAccessor.HttpContext;
}

I can see that :

  1. I don't retrieve correctly HttpContext.Session, it throw an InvalidOperationException
  2. The request is not correct : the Path is null, and this should be something like '/Home/Index'

I re-used SessionMiddleware in my project and I can see that user session is correctly restored into the HttpContext, but in my Policy I'd get the wrong one. SessionMiddleware is correctly added before MVC Middleware. Any ideas ?

SOLUTION (thanks @JoeAudette) Keep accessor until you need HttpContext.

public TokenValidHandler(IHttpContextAccessor contextAccessor)
{            
    _accessor = contextAccessor;
}

protected override void Handle(AuthorizationContext context, TokenValidRequirement requirement)
{
    // Right context ...
    var contextHttp = _accessor.HttpContext;
}

Solution

  • instead of getting the context in the constructor, try keeping the contextAccessor around and wait to get the actual context until just before you need to check it