4

我开发了一个在 Visual Studio 2012 中运行良好的 ASP.NET MVC 4 Web 应用程序 (.net 4.5)。在 Windows Server 2008 R2 上部署到 IIS 7 后,我的控制器内的 HttpContext.Session 对象似乎为空。我创建了一个简单的测试 ASP.NET MVC 4 应用程序来演示该问题。

在我的测试应用程序中,我有一个简单的家庭控制器

public class HomeController : Controller
{
    public ActionResult Index()
    {
          if ( HttpContext != null && HttpContext.Session != null )
          {
              HttpContext.Session[ "test" ] = "a string in session state";
              ViewBag.Info = HttpContext.Session[ "test" ];
              return View();
          }
          else
          {
              if ( HttpContext == null )
              {
                  ViewBag.Info = "beeeeuuuuu - HttpContext = null!!!";
              }
              else if ( HttpContext.Session == null )
              {
                    ViewBag.Info = "beeeeuuuuu - Session = null!!!";
              }
              return View();
          }

    }
}

我的 Index.chtml 视图看起来像这样:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
This is a simple test
<p>@ViewBag.Info</p>

所以当我运行应用程序时,我得到了我所期望的:

Index
This is a simple test 
a string in session state

但在我将应用程序部署到 Web 服务器后,网站会显示以下页面,指示 Session 对象为空:

Index
This is a simple test 
beeeeuuuuu - Session = null!!!

Web 应用程序部署到在 ASP.NET v4.0 应用程序池(集成管道)下运行的默认网站。

我已经使用 aspnet_regiis -ir 在服务器上重新安装了 ASP.NET,但这并没有帮助。会话状态在 ISS 服务器上启用(在 Proc 中)。我希望任何人都可以在这里帮助我,因为我试图解决这个问题已经有一段时间了。

非常感谢提前和亲切的问候。

更新:我还使用 .NET 4.0 而不是 4.5 测试了 ASP.NET MVC 4 构建,并且存在同样的问题。我还部署了一个 ASP.NET 网页应用程序 (.NET 4.0),它运行良好(后面的代码中的 HttpContext.Current.Session 不为空)。

更新二:我还尝试将会话状态存储在数据库中,该数据库在我的开发机器上运行良好,但在生产服务器上遇到了同样的问题(HttpContext.Session 仍然返回 null)。

4

2 回答 2

28

我找到了解决方案。您必须添加和删除 SessionStateModule:

  <configuration>
  ...
  <system.webServer>
    ...
    <modules>
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      ...
    </modules>
  </system.webServer>
</configuration>

我不知道为什么微软不把它添加到项目模板的 web.config 中?

于 2013-07-31T11:59:18.870 回答
0

当我部署我的应用程序时,我认为Session我的控制器中为空,但我错了。原来我错过了 lambda 表达式的微妙之处。虽然这不是提问者的解决方案,但这个问答在搜索中排名很高,所以我希望这个答案可以为其他人节省一些时间。

我的控制器最初包含如下内容:

HostingEnvironment.QueueBackgroundWorkItem(ct => Foo(ct, Bar(Session)));

Bar是一个从会话中获取值的静态方法,它抛出了一个试图访问其参数的 NRE。我更改了我的控制器代码如下,一切都很好:

var bar = Bar(Session);
HostingEnvironment.QueueBackgroundWorkItem(ct => Foo(ct, bar));

谜团在于为什么在我的本地机器上测试时原始代码完全可以工作!

于 2019-06-10T19:04:09.693 回答