Search code examples
asp.netasp.net-mvcsessionglimpse

Glimpse - How do I access HttpContext.Session inside an IRuntimePolicy


I'm enjoying the Glimpse web diagnostics platform for ASP.NET, and would like to deploy it to production to capture data about end-user interactions to help with troubleshooting. Obviously I'd like to lock down access so not just anyone can access all the data Glimpse captures.

I've implemented GlimpseSecurityPolicy (an instance of IRuntimePolicy) and confirmed via a debug breakpoint that the Execute method is invoked when I request a page on my site.

The problem is that I can't interrogate the session associated with the current HttpContext. I'm able to get an instance of the context by calling policyContext.GetHttpContext()... but that context object has a null Session property. The property is also null if retrieved via HttpContext.Current.

When accessing the current context elsewhere in my main application code (via HttpContext.Current), the Session property is populated and I can interact with it just fine.

So I have two related questions:

  • Why is the Session property not populated?
  • How can I get access to the current Session from inside a Glimpse IRuntimePolicy?

If it helps, I'm running Glimpse 1.8.5 in a website running ASP.NET MVC 5.2. Also I've left the IRunTimePolicy ExecuteOn property returning the default return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource;.


Solution

  • The reason is that your IRuntimePolicy is actually being executed to late in the pipeline. As you said, you kept the default value for the ExecuteOn property, and the session is closed before that RuntimeEvent.

    If you change the value for ExecuteOn to RuntimeEvent.BeginSessionAccess | RuntimeEvent.ExecuteResource then the Session property should be available inside your IRuntimePolicy implementation.

    Regarding the RuntimeEvent.ExecuteResource this one is only needed if your IRuntimePolicy is actually used to enforce resource access aka used for Glimpse Authorization, see this blog post for more details. So if that is not the case, then you can remove it as well.