确定 ASP.NET 会话是否已启用

5
什么是在C#中检测ASP.NET会话是否启用的最佳方法?我不想使用try-catch块,Sessions!= null会抛出异常。祝好。
5个回答

7

如果您使用 HttpContext.Current,将不会发生异常:


if(HttpContext.Current.Session != null)
{
    // Session!
}

这个很好地运行着,没有抛出异常。我不知道为什么@KeithAdler说它会抛出异常。 - FLICKER
Page.Session 抛出异常,但 HttpContext.Session 不会。 - Markus Jarderot
当在dot net 6中未启用会话时,我确实看到“if (HttpContext.Session!= null)”抛出异常:System.InvalidOperationException:尚未为此应用程序或请求配置会话。 - Kris
在较新的 .NET 版本中,使用 HttpContext.Features.Get<ISessionFeature>()?.Session != null 是一种解决方法。 - Kris

2

1
以下是如何确定会话状态是否已启用的方法:
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)

1

对于 .NET 6,您可以使用以下内容:

if (HttpContext.Features.Get<ISessionFeature>()?.Session != null)
{
}

0
你可以使用类似这样的东西(伪代码)
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
}

由于会话状态也可以通过页面指令和其他配置文件(machine.config或位于更高目录级别的web.config)启用,因此这个答案至少是不完整的,最坏的情况下是完全错误的。 - wensveen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接