Establishing cookie based session with WebServices and HttpWebRequest
Create cookie based session with HttpWebRequest
One common requirement for Http based application to maintain the session state within the application, if your http based application is using the System.Net.HttpWebRequest class, then you could use Cookiecontainer property to send and recieved the cookies. Important thing to note that you should create a single CookieContainer instance and use it across all applications
Following example code snippet shows the sending and recieving the cookies from client application.
CookieContainer myContainer = new CookieContainer();
// following line will add a cookie in container, which would be for all urls on the domain myDomainstr
myContainer.Add(new Cookie("name","value","/",myDomainstr));
HttpWebRequest request1 = (HttpWebRequest) WebRequest.Create(httpUrlString);
request1.CookieContainer = myContainer; // use this same container for all requests in your app
HttpWebResponse response = (HttpWebResponse) request.GetResponse(); //you can check cookies on response.Cookies
..........
...........
HttpWebRequest request2 = (HttpWebRequest) WebRequest.Create(httpUrlString2);
request2.CookieContainer = myContainer; //all relevant cookies recieved on request1 would be automatically included in request because of same Cookiecontainer instnce.
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Create cookie based session with WebServices
If application want to use WebServices with cookie based session variables to execute service (ex. UserId of current ASP.Net session). This could be done via using the CookieContainer class and no need to add extra parameter inside the webservice call.
Following code demonstrate the setting of userID on the webservice from client side, In this example adarshk_srv.RunSoap is the WebService proxy object on client side
adarshk_srv.RunSoap RunService = new adarshk_srv.RunSoap();
RunService.CookieContainer = new System.Net.CookieContainer ();
RunService.CookieContainer.Add (new Uri(RunService.Url),new Cookie ("userName",ā€¯adarshk");););
On the server side WebService implementor could access the cookies send by the client from the HttpContext as shown below
if(Context.Request.Cookies != null && context.Request.Cookies["userName"] == "adarshk")
{
// access data specific to adarshk
}
else
{
// return the general data
}
This posting is provided "AS IS" with no warranties, and confers no rights