Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

asp.net - 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.Create(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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...