2

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;
}
Christophe Gigax
  • 3,211
  • 4
  • 25
  • 37
  • 3
    instead of getting the context in the constructor, try keep the contextAccessor around and wait to get the actual context until just before you need to check it – Joe Audette May 03 '16 at 15:22
  • That was the solution :) Many hours just for this ... Maybe you can post a response so I can mark it as resolve – Christophe Gigax May 03 '16 at 15:33
  • glad that worked, I have posted it as an answer – Joe Audette May 03 '16 at 15:37
  • Ideally, you'd likely want to rework your filter as an authentication middleware and use the new claims-based authorization block, that doesn't require implementing custom code. – Kévin Chalet May 03 '16 at 15:48
  • @Pinpoint I use Policy for specific authentication action and claims-based authorization, have you an exemple of what you'd said ? – Christophe Gigax May 04 '16 at 07:37

1 Answers1

2

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

Joe Audette
  • 35,330
  • 11
  • 106
  • 99