Sometimes you need to know if Session is enabled or not in an ASP.NET web site.

I recently came across this while doing some work for a client, wrapping some User Controls they had written in Web Parts for a SharePoint site.

By default, Session is turned off in SharePoint – and please don’t turn it on. There are better ways to handle things, besides Session, but that is the subject for a different post.

Anyway, the Session stuff wasn’t needed in SharePoint, so I just needed a quick way to determine if it was available. If not, I would just skip the code-path that used it. I didn’t have time to re-write all of the User Controls to not use Session, as it was a short engagement.

So, if you’ve read this far, here is the code:

if (HttpContext.Current.Session != null)

{

    // then use session

}

 

That is all there is to it…