How will make your web services stateful?
Or
This question can be asked as how to implement session in your web services?
Web services run on HTTP with underlying message protocol as SOAP, now since HTTP in its nascent form is stateless so are XML web services in .net. Now the question arises if web services are stateless, then how can we make our web services store user session information… Let’s look at the approach.
First Things first, we will make use of some of the properties of WebMethod attribute to enable session in a web service as follows
[WebMethod (EnableSession=true)]
public void SessionStart()
{
Session["username"] = "Shakti";
}
[WebMethod(EnableSession = true)]
public string SessionEnd()
{
return "Hello " + Session["username"];
}
Now create a new project which will act as a client, it can be a windows form application or a Web site. For this sample I am taking a windows form..
In client add a reference to the service created above.
Add below code to access the service
localhost.Service obj = new localhost.Service();
obj.CookieContainer = new System.Net.CookieContainer();
obj.SessionStart();
Console.WriteLine( obj.SessionEnd());
And here is the output
Hello Shakti
If you look at client code closely you will see below line
obj.CookieContainer = new System.Net.CookieContainer();
How it works?
We are storing session information in the proxy itself which is a part of client process so nothing is being stored on the server.
Nice Article Sir .... Like It...
ReplyDeleteHope so u will Give a Blog about MVC 2 or 3 ...
ReplyDeleteAfter creating the proxy of web services the object doesn't have any cookie container property so I can't access the session variables in the particular web method. In Visual Studio 2010 can we use session in web service enable session= true already mention in web method.
ReplyDeletePlease Reply me as soon as possible sir.
anc.kunal@gmail.com
good one!
ReplyDelete