HttpContext.Session在一个环境中包含密钥,但在另一个环境中不包含密钥

时间:2020-04-29 09:11:15

标签: c# asp.net-core-mvc session-variables

我有一个.NET Core 2.1 MVC项目,我已按照this link的步骤逐步将其升级到.NET Core 3.0。该项目使用IHttpContextAccessor将多个值存储在HttpContext.Session集合中,当我在开发环境中使用F5启动该项目时,一切似乎都在工作。但是,当我将项目发布到测试服务器时,会话密钥集合为空,并且值不再存在。

因为这两种环境下的代码应该相同,所以我认为它必须与项目的会话配置方式有关,但是我无法找到解决方案。这是我的Startup.cs的配置方式:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddDistributedMemoryCache();
    services.AddSession();
    ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseSession();
    ...
}

我尝试使用Newtonsoft序列化Session对象,但结果非常有限:

{"IsAvailable":true,"Id":"44b1d511-e0cb-a1a3-c117-84033b80df25","Keys":[]}

不幸的是,该项目无法单独运行,而是依赖于外部输入,因此需要花费大量时间来测试每种情况。在我完全剥离该项目之前,我想知道是否有人对我可以做些什么找出原因的建议。

2 个答案:

答案 0 :(得分:0)

我今天有类似的问题。因此,我通过从已发布项目生成的web.config进行了更新,以添加以下代码。

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

注意:我正在以独立模式运行应用程序,并且ApplicationPool设置为无托管代码,最后我使用urlrewrite将代理反向转换为localhost:5000以便在iis上运行.net核心应用程序

答案 1 :(得分:0)

我终于弄清楚了问题所在,这是一个错误。在# example polygon dataframe r1 <- cbind(c(180114, 180553, 181127, 181477, 181294, 181007, 180409,180162, 180114), c(332349, 332057, 332342, 333250, 333558, 333676, 332618, 332413, 332349)) r2 <- cbind(c(180042, 180545, 180553, 180314, 179955, 179142, 179437, 179524, 179979, 180042), c(332373, 332026, 331426, 330889, 330683, 331133, 331623, 332152, 332357, 332373)) r3 <- cbind(c(179110, 179907, 180433, 180712, 180752, 180329, 179875, 179668, 179572, 179269, 178879, 178600, 178544, 179046, 179110), c(331086, 330620, 330494, 330265, 330075, 330233, 330336, 330004, 329783, 329665, 329720, 329933, 330478, 331062, 331086)) r4 <- cbind(c(180304, 180403,179632,179420,180304), c(332791, 333204, 333635, 333058, 332791)) sr1 <- Polygons(list(Polygon(r1)),"r1") sr2 <- Polygons(list(Polygon(r2)),"r2") sr3 <- Polygons(list(Polygon(r3)),"r3") sr4 <- Polygons(list(Polygon(r4)),"r4") sr <- SpatialPolygons(list(sr1,sr2,sr3,sr4)) srdf <- SpatialPolygonsDataFrame(sr, data.frame(poly=c("r1","r2","r3","r4"), row.names=c("r1","r2","r3","r4"))) # load some points to test data(meuse) points <- meuse[,c('x','y')] coordinates(points) = ~x+y # test which polygon each point is over result <- over(points, srdf) # check the results plot(points, col=result$poly) legend("topleft", legend=levels(result$poly), pch=16, col=c('black','red','green','blue')) polygon(r1, border='black') polygon(r2, border='red') polygon(r3, border='green') polygon(r4, border='blue') 中将会话作为服务添加时,似乎忘记了配置cookie设置。所以代替这个:

Startup.cs

应该是这样的:

services.AddSession();

为什么我不能在我的本地环境上使用它仍然无法解决。可能与以下事实有关:我从本地主机(与MVC项目相同的域)上的测试页访问MVC项目,但在我的测试服务器上,MVC项目位于不同的域中。尽管如此,现在一切都像魅力一样。