2

I need to store a collection of strings in session, and I have a web method that I'm calling through a jQuery ajax call:

[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;
}

I'm getting an error when I try to add the id to session:

Object reference not set to an instance of an object.

Am I doing this wrong?

3 Answers 3

5

You need to explicitly enable session access using the EnableSession property:

[WebMethod(EnableSession = true)]

Note that your else logic will fire in the case HttpContext.Current.Session == null, which is likely the cause of the NullReferenceException.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to change [WebMethod] to [WebMethod(EnableSession = true)] in order to access the current session.

Then you can access the current session like so:

HttpContext.Current.Session

Comments

0

You need to enable session for the web method, change the attribute to

[WebMethod(EnableSession = true)] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.