我需要在 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/