How to keep session alive between two calls to a web service in a c# application?
This is quite straight forward.
I'm calling a web-service (.asmx, with session enabled) from a c# application.I want each call to be with the same session key as the previous one (as opposed to creating a new session key each time).
Here's my (nothing-out-of-the-ordinary) code:
public string invokeMethod(string methodUrl)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Crea开发者_如何学Gote(methodUrl);
req.Method = "GET";
req.ContentLength = 0;
var result = new StringBuilder();
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
StreamReader sr = new StreamReader(res.GetResponseStream());
result.Append(sr.ReadToEnd());
}
return result.ToString();
}
Now I want to call it again, in the same session.
Added: Thanks to Waleed's answer, I think I should be doing (after retrieving the session id) something like:
Added once more: This is how it's done:if (!string.IsNullOrEmpty(currentSessionID))
{
Cookie cookie = new Cookie("ASP.NET_SessionId", currentSessionID);
cookie.Domain=myDomain; //Will not work without this line!
req.CookieContainer.Add(cookie);
}
Thanks again.
If I understand the question correctly, I believe you'll need to get the session cookie from the response (the first time you call the web service) and add it to the request in the subsequent calls.
Edit:
Using CookieContainer is the correct way but be aware that it's null by default so you'll have to to assign a CookieContainer object to the property before making the request (see the example code in the MSDN's article).
As to the cookie name, the default name for ASP.NET session cookie is ASP.NET_SessionId, but the name can be different as it can be changed in web.config, or they might not be using ASP.NET sessions (their own implementation for example), so you'll have to check the cookies you get from the domain of that application (You can use an HTTP sniffer like Fiddler, or more easily if you're using FireFox or Chrome, you can check the names and contents of the cookies you get from that domain in the options dialog box).
There is a good discussion of using ASP.NET session state with web services on MSDN here:
http://msdn.microsoft.com/en-us/library/aa480509.aspx
From first call, look after ASP.NET_SessionId
value in response, this is session Id by default.
Then add it to next call (see below):
http://support.microsoft.com/?kbid=899918
精彩评论