How can I access session in a webmethod?

You can use:

HttpContext.Current.Session

But it will be null unless you also specify EnableSession=true:

[System.Web.Services.WebMethod(EnableSession = true)]
public static String checaItem(String id)
{ 
    return "zeta";
}

For enable session we have to use [WebMethod(enableSession:true)]

[WebMethod(EnableSession=true)]
public string saveName(string name)
{
    List<string> li;
    if (Session["Name"] == null)
    {
        Session["Name"] = name;
        return "Data saved successfully.";

    }

    else
    {
        Session["Name"] = Session["Name"] + "," + name;
        return "Data saved successfully.";
    }


}

Now to retrive these names using session we can go like this

[WebMethod(EnableSession = true)]
    public List<string> Display()
    {
        List<string> li1 = new List<string>();
        if (Session["Name"] == null)
        {

            li1.Add("No record to display");
            return li1;
        }

        else
        {
            string[] names = Session["Name"].ToString().Split(',');
            foreach(string s in names)
            {
                li1.Add(s);
            }

            return li1;
        }

    }

so it will retrive all the names from the session and show.


There are two ways to enable session for a Web Method:

1. [WebMethod(enableSession:true)]

2. [WebMethod(EnableSession = true)]

The first one with constructor argument enableSession:true doesn't work for me. The second one with EnableSession property works.

Tags:

C#

Session