c# - 向 session 添加值时出现 NullReferenceException

标签 c# asp.net

我需要在 session 中存储字符串集合,并且我有一个通过 jQuery ajax 调用来调用的 Web 方法:

[WebMethod]
public string AddIdToSession(string userId)
{
    List<string> userIds = new List<string>();

    if (HttpContext.Current.Session != null && 
        HttpContext.Current.Session["userIds"] != null)
    {
        userIds = (List<string>)Session["userIds"];
        userIds.Add(userId);
        HttpContext.Current.Session["userIds"] = userIds;
    }
    else
    {
        userIds.Add(userId);
        HttpContext.Current.Session.Add("userIds", userIds);  // error here
    }

    return userId;
}

当我尝试将 ID 添加到 session 时遇到错误:

Object reference not set to an instance of an object.

我这样做错了吗?

最佳答案

您需要使用 EnableSession 显式启用 session 访问属性:

[WebMethod(EnableSession = true)]

请注意,您的 else 逻辑将在 HttpContext.Current.Session == null 的情况下触发,这可能是导致 NullReferenceException 的原因>.

关于c# - 向 session 添加值时出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14444924/

相关文章:

c# - "large"滚动时数据集崩溃 Gridview。 Win32错误

c# - 指定的架构无效。错误 : error 0002: Request failed

c# - 使用 Math.NET C# 计算导数

c# - 在 NET.Core 上的 VS Code 中对一个非常简单的 WebApi 进行故障排除

c# - 如何使用 JavaScript 或 JQuery 获取 ASP.net 中生成的控件的 ID

javascript - 突出显示选定的表格单元格 C# 菜单

c# - 办公文件转PDF

c# - Lambda表达式获取3个字段值

jquery - 从代码隐藏中打开 jQuery 对话框

c# - 在 ASP.NET MVC 中编写 XML 文件?