20 March 2012

Using Session State in a Web Service

In my web application i have used web services many time. Now i need to pass session variable to the web service method to get data form the database based on the session value. When i am passing session value I got an error. After searching i found the solution to use HttpSession in web methods. It is very simple to resolve this issue i.e enable the session state before using it. This can be done by using following attribute.
[WebMethod(EnableSession=true)] //C#
<WebMethod(EnableSession:=true)] 'VB.net

Example: 
Passing Session value
Session["Value"] = 3; 
Access this session variable (Session["Value"] ) in Add Web Method.
Example:

[WebMethod(Description = "adds x , y and  Value session")]
public int Add(int x, int y)
{
   return (x + y) + (int)Session["Value"] ;
}
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  Value session")]
public int Add(int x, int y)
{
return(x + y) + (int)Session["Value"] ;
}
Once you specify these lines over your web method you can use the session object naturally.

No comments:

Post a Comment