【问题标题】:Determine if ASP.NET Sessions are enabled确定是否启用了 ASP.NET 会话
【发布时间】:2013-08-02 01:24:44
【问题描述】:

在 C# 中进行布尔测试以确定 ASP.NET 会话是否启用的最佳方法是什么?我不想使用 try-catch 块并且 Sessions != null 会引发异常。

问候。

【问题讨论】:

    标签: c# asp.net session


    【解决方案1】:

    如果你使用HttpContext.Current,你不会得到异常:

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

    【讨论】:

    • 这很好用并且不会抛出异常。我不知道为什么@KeithAdler 说它抛出异常。
    • Page.Session 会抛出异常,但 HttpContext.Session 不会。
    【解决方案2】:

    您想查询Web.config 中的EnableSessionState 属性。

    【讨论】:

      【解决方案3】:

      您可以通过以下方式确定会话状态是否已启用:

      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)
      

      【讨论】:

        【解决方案4】:

        你可以使用这样的东西(伪代码)

        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)启用,所以这个答案至少是不完整的,最坏的情况是完全错误的.
        猜你喜欢
        • 1970-01-01
        • 2015-06-19
        • 1970-01-01
        • 1970-01-01
        • 2020-10-15
        • 2010-12-09
        • 2014-05-11
        • 2012-01-24
        • 1970-01-01
        相关资源
        最近更新 更多