Using ASP.NET Session State in a Web Service
Since yesterday, I am having problem creating a Session State in a Web Service. First the session creates a unique ID everytime you invoke the method. Second you need to tell the web service method that you will use session state. I've seen a lot of example out there, but I am having trouble increment the hits of my web service method. I think there is a problem with their code. So here's what I did:
1.) First Create the Web Methods. Make sure your set the EnableSession to true:
(One is to get the value of the session changed, the second one is to change the session value as parameter)
[WebMethod(EnableSession = true)]
public object getsession()
{
return Session["MySession"];
}
[WebMethod(EnableSession = true)]
public void changesession(object val)
{
Session["MySession"] = val;
So how do you consume this web methods and use session at the same time on web service? First create a cookie that will be your ID for your service, then put this cookie on a session, so that whenever you will need this cookie with the same ID for your web service session, you can just call the session name. Here is an example:
localhost.Service myService; //declare your web service variable
protected void Button1_Click(object sender, EventArgs e)
{
System.Net.CookieContainer cookies = new System.Net.CookieContainer(); //declare your cookie as your ID for your Session's web service
object x;
Session["MyCookie"] = cookies; //put the cookie on a Session
if (myService == null)
{
myService = new localhost.Service();
myService.CookieContainer = (System.Net.CookieContainer)Session["MyCookie"]; //declare your CookieContainer for your service which is in your Session, which you can always call
Session["MySession"] = "Hello World" ;
myService.changesession(Session["MySession"]); //change your Session value on your web service method which is saved on your unique CookieContainer
}
protected void Button2_Click(object sender, EventArgs e)
{
if (myService == null)
{
myService = new localhost.Service();
myService.CookieContainer=(System.Net.CookieContainer)Session["MyCookie"]; //declare your CookieContainer again which is in your Session, this CookieContainer should have specific value
Session["MySession"] = myService.getsession(); //retrieve the value of your Session value on your web service method
}
It was first confusing, but with little practice and applying it in a mock-up application, you can understand the logic behind declaring a Session inside a web service which is important for methods that needs the theory behind it.