Friday, July 31, 2009

Enable session state on a Web Methods, Web service

By default each web method session state is disabled.
Example:

Declare and assign a session variable in Global.asax Session_Start.

void
Session_Start(objectsender, EventArgs e)
{
Session["Overhead"] = 3;
}

Access this session variable (Session["Overhead"] ) in Add Web Method.

[WebMethod(Description = "adds x , y and Overhead session")]
public int Add(int x, int y)
{
return (x + y) + (int)Session["Overhead"] ;
}

This will not work and throws an error. To avoid this needs to enable session state in each web metods.

Example:

[WebMethod(EnableSession = true, Description = "adds x , y and Overhead session")]
public int Add(int x, int y)
{
return(x + y) + (int)Session["Overhead"] ;
}

In this above example in the [WebMethod] attribute EnableSession property has explicitily set to true. Now the Add web method is retrieving Session["Overhead"] variable’s value. All you have to do is just enable the session in [WebMethod] attribute.


0 comments:

My Achievements

Member of

Blog Archive

Followers