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 :
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;
}
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