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 don't retrieve correctly HttpContext.Session, it throw an InvalidOperationException
- 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;
}