views:

849

answers:

3

Hi,

we are using a web service for a web site to communicate with an external server. External server ask for a session id.

Our following code ask external server:

HttpWebRequest webRequest = WebRequest.Create(ExtUrl) as HttpWebRequest;
webRequest.Credentials = new NetworkCredential(ExtAccountToUse, ExtPassword);
HttpWebResponse webResponse;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";                
StreamWriter writer = new StreamWriter(webRequest.GetRequestStream());
 writer.Write(xmlOutput);
writer.Close();               
webResponse = webRequest.GetResponse() as HttpWebResponse;

Is it possible to get a session id to send to external server ?

Thanks for your time

A: 

as far as getting session ID is concerned you can get it using:

Session.SessionID

but I don't think session id on your server is of any interest to external server.

TheVillageIdiot
I doubt using the current servers session ID is useful in talking to an external server.
AnthonyWJones
I'm not using this way but thanks for your time
Xstahef
+1  A: 

That depends on the type of server you are sending the request to. For example, if you have an IIS hosted site, it expects a session id inside a cookie named ASP.NET_SessionId (or on the request string). If you have a Java servlet engine on the other side, it expects a cookie called JSESSIONID (or a request path parameter jsessionid).

So it depends. However, setting cookies inside a HttpWebRequest is not difficult. You can use the property CookieContainer:

CookieContainer cookies = new CookieContainer();
cookies.Add(new Cookie("ASP.NET_SessionId", sessionId));
request.CookieContainer = cookies;

The session identifier you store inside the cookie should have a particular format and again, this depends on the server type at the other end. In ASP.NET by default the class SessionIDManager is used to produce and validate session ids. This class is hard to reuse because it requires an HttpContext. However, you could check with Reflector how it generates a session id.

Ronald Wildenberg
+1  A: 

If you mean the external server requires an existing session ID that identifies a session created by prior requests sent to it then you need to maintain an instance of a CookieContainer for all of the requests involved.

 CookieContainer myExternalServerCookies = new CookieContainer();

With every HttpWebRequest you use to talk to the external server include this line:-

 request.CookieContainer = myExternalServerCookies;

Now when the external server sets a session cookie, it will see that cookie in subsequent requests.

AnthonyWJones