【发布时间】:2013-08-02 01:24:44
【问题描述】:
在 C# 中进行布尔测试以确定 ASP.NET 会话是否启用的最佳方法是什么?我不想使用 try-catch 块并且 Sessions != null 会引发异常。
问候。
【问题讨论】:
在 C# 中进行布尔测试以确定 ASP.NET 会话是否启用的最佳方法是什么?我不想使用 try-catch 块并且 Sessions != null 会引发异常。
问候。
【问题讨论】:
如果你使用HttpContext.Current,你不会得到异常:
if(HttpContext.Current.Session != null)
{
// Session!
}
【讨论】:
Page.Session 会抛出异常,但 HttpContext.Session 不会。
您想查询Web.config 中的EnableSessionState 属性。
【讨论】:
您可以通过以下方式确定会话状态是否已启用:
PagesSection pagesSection = ConfigurationManager.GetSection("system.web/pages") as PagesSection;
if ((null != pagesSection) && (pagesSection.EnableSessionState == PagesEnableSessionState.True))
// Session state is enabled
else
// Session state is disabled (or readonly)
【讨论】:
你可以使用这样的东西(伪代码)
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
}
【讨论】: