Pradyummna Reddy
Pradyummna Reddy

Reputation: 53

Saving array in session c# error

I am trying to save array in session and trying to get it back. The following is the code. But i get the following error when i invoke the WebMethod. I am using c#. VS2010

error:

System.NullReferenceException: Object reference not set to an instance of an object. at xmlRW1.Service1.logic() in C:\Users\uydarp\Documents\Visual Studio 2010\Projects\xmlRW1\xmlRW1\Service1.asmx.cs:line 86

[WebMethod]
    public int logic()
    {
        int[] myArray = { 1,2,3,4};
        Session["MyArray"] = myArray; 

        int[] myArray2 = (int[])Session["MyArray"];
        int firstElement = myArray2[0];

        return firstElement;
    }

Upvotes: 0

Views: 101

Answers (1)

Kenneth
Kenneth

Reputation: 28747

SessionState is disabled by default in asmx services. You can enable it by changing the WebMethod attribute to explicitly enable it:

[WebMethod(EnableSession = true)]
public int logic()
{
    int[] myArray = { 1,2,3,4};
    Session["MyArray"] = myArray; 

    int[] myArray2 = (int[])Session["MyArray"];
    int firstElement = myArray2[0];

    return firstElement;
}

Upvotes: 5

Related Questions