【问题标题】:Session values returning null会话值返回 null
【发布时间】:2016-09-23 21:24:45
【问题描述】:

我在本地运行一个 ASP MVC 站点 (.Net 4.5) 并在尝试从会话中检索值时遇到问题。我从静态助手调用代码 类类似如下:

Helpers.cs

public static void SetSessionValue(string key, object value)
{       
    HttpContext.Current.Session[key] = value;
}

public static object GetSessionValue(string key)
{   
    return HttpContext.Current.Session[key];
}

AjaxController.cs

public ActionResult SetUserName(string username)
{
    Helpers.SetSessionValue("username", username);
}

public ActionResult GetUserName()
{
    var username = Helpers.GetSessionValue("username"); 
    return Json(new { valid = true, username });
}

上面的用户名是一个例子,但我有多个发生这种情况的情况,每次键的值为空,但键仍然存在。我进一步去了 on 并将以下内容添加到 SetSessionValue 以进行测试:

public static void SetSessionValue(string key, object value)
{       
    HttpContext.Current.Session[key] = value;
    var test = HttpContext.Current.Session[key];
}

变量 test 将填充该值。我仔细检查了所有变量名。键仍然存在于集合中,但值消失了。

尝试的解决方案

解决方案 1 - HttpContext.Current.Session null item

我在我的网络配置中设置了以下内容,没有运气

<sessionState mode="InProc" timeout="20" />

解决方案 2 - HttpContext.Current.Session is null when routing requests

我在我的网络配置中设置了以下内容,没有运气

<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>

我尝试过的其他项目

  • 确保 &lt;httpCookies requireSSL="true" /&gt; 不在 web.config 中
  • 尝试使用 SSL 启用和运行
  • 在发布模式下运行
  • 确保没有Session.Abandon();Session.Clear();
  • 确保没有运行病毒扫描
  • 进行了搜索以确保我没有在其他地方更新
  • 确保我的 ASP.NET 状态服务 正在运行
  • 尝试添加[WebMethod(EnableSession = true)]
  • 我已确保我已启用 Cookie

【问题讨论】:

  • 检查您的浏览器是否启用了cookies
  • 刚刚再次检查以确保它们是...
  • 您是否真的有可能为第二个参数调用带有 null 的 SetSessionValue/SetUserName?可能会在调用 SetSessionValue 时添加一些日志记录。
  • 我已经确认过了。另外在上面更新的 SetSessionValue 中进行了测试。我确定我正在传递一个值,只是它离开方法后似乎会丢失它
  • 您没有在 GetUserName 方法中设置用户名变量..请更新代码

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


【解决方案1】:

发现了问题……感觉自己像个白痴。尽管我去关闭了 IIS Express 中的所有实例和我正在运行的服务,但该项目的另一个实例正在某个地方运行,从而混淆了我的会话项目。

为了确保我的一切都是最新的,我进去修改了端口号 (右键项目 -> 属性)

这样做之后,一切都按预期进行。这可能是一个非常独特的案例,但想发帖以防万一有人遇到类似情况。

【讨论】:

    【解决方案2】:

    您几乎检查了所有内容,只需检查无 cookie 模式,看看会发生什么,我猜您的 cookie 有问题:

    <sessionState mode="InProc" cookieless="true" />
    

    【讨论】:

    • 哈哈,刚看到你的回答,真的很牛逼,不过还是搞定了
    • 酷,很高兴你发现了问题。无论如何,cookieless 可能是某些浏览器的解决方案。
    猜你喜欢
    • 2015-10-11
    • 2019-06-08
    • 2017-07-03
    • 2021-05-08
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    相关资源
    最近更新 更多