3

I know that the SessionState attribute can be used to set the SessionStateBehavior for requests to a particular MVC controller. My question is, how can I determine the current request's SessionStateBehavior programatically? I see that HttpContext has an internal property for this, but is there any way to get at this publicly?

In particular, I'd like to know whether the session state behavior was disabled.

ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152

2 Answers2

2

HttpContext.Current.Session == null will check for a disabled session HttpContext.Current.Session.IsReadOnly will check for a read-only session

Martin Randall
  • 308
  • 2
  • 9
0

Looking into this further, it seems like the only surefire solution to the exact problem posted above is to access the internal SessionStateBehavior property using reflection:

var behavior = (SessionStateBehavior)typeof(HttpContext)
    .GetProperty("SessionStateBehavior", BindingFlags.Instance | BindingFlags.NonPublic)
    .GetValue(HttpContext.Current);

However, for the specific case of checking whether session state has been disabled, in most scenarios a simple null check against HttpContext.Current.Session should suffice. I'm basing this on the reasons listed in this question for why that property may be null.

Community
  • 1
  • 1
ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152