views:

109

answers:

3

What is the best way to do a boolean test in C# to determine if ASP.NET sessions are enabled? I don't want to use a try-catch block and Sessions != null throws an Exception.

Regards.

+2  A: 

You want to interrogate the EnableSessionState property in Web.config.

Vinay Sajip
A: 

You will not get an exception if you use HttpContext.Current:

if(HttpContext.Current.Session != null)
{
    // Session!
}
John Rasch
This throws and exception.
Nissan Fan
+1  A: 

You can use something like this(Pseudo code)

XmlDocument document = new XmlDocument();

document.Load("Web.Config");

XmlNode pagesenableSessionState = document.SelectSingleNode("//Settings[@Name = 'pages']/Setting[@key='enableSessionState']");

if(pagesenableSessionState .Attributes["value"].Value =="true)

{

//Sessions are enabled

}

else

{

//Sessions are not enabled

}

Neil