How to maintain session using HttpWebRequest and SetCookies?

  • Thread starter Thread starter Peter Qian
  • Start date Start date
P

Peter Qian

Hi,
I'm working on a windows form based program that can log into a web
service (Apache based, https is used for auth). I was able to post the login
data and obtain a sessionID. However I'm not sure how to maintain this id
over multiple requests. Here are my code:


Globle Varibles
private static int timeOut = 20000;
private CookieContainer cookieContainer; /* other cookies */
private string headerCookie; /* often stores session info */
private string cookieHeader;

1. Login Routine:

public bool OpenLoginSession( string url,
System.Collections.Specialized.NameValueCollection param )
{
WebHeaderCollection headers;
bool statusOK;

HttpWebRequest loginReq =
(HttpWebRequest)WebRequest.Create(url);
cookieContainer = new CookieContainer();
HttpWebResponse loginRes;
//
// Login Request
//
loginReq.CookieContainer = cookieContainer;
loginReq.KeepAlive = false;
loginReq.Method = "POST";
loginReq.AllowAutoRedirect = false;
//
// Build POST stream
//
System.Text.StringBuilder query = new StringBuilder();
query.Append("?");
foreach( string key in param.Keys )
{
query.AppendFormat("{0}={1}&", key, param[key]);
}
byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(
query.ToString() );
Stream os = loginReq.GetRequestStream();
os.Write( buf, 0, buf.Length );
os.Close();
//
// POST the info
//
loginRes = (HttpWebResponse)loginReq.GetResponse();
cookieHeader = cookieContainer.GetCookieHeader(
loginReq.RequestUri );


if ( loginReq.HaveResponse && loginRes.StatusCode ==
HttpStatusCode.OK )
{
headers = loginRes.Headers;
if ( headers["Set-Cookie"] != null )
{
headerCookie = headers["Set-Cookie"];
}

statusOK = true;
}
else
statusOK = false;

loginRes.Close();
return(statusOK);

}

Note, after this routine, "cookieHeader" is an empty string for some reason,
and headerCookie stores the sessionID correctly.

2. Browsing Routine

public void BrowseSecuredUrl( string url )
{
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create(url);
HttpWebResponse res;

cookieContainer = new CookieContainer();
req.CookieContainer = cookieContainer;
req.KeepAlive = false;
req.Headers.Add("Cookie", headerCookie);

cookieContainer.SetCookies( req.RequestUri ,
cookieHeader );//error here

res = (HttpWebResponse)req.GetResponse();
...
res.Close();

}

The error I'm getting "is An error has occurred when parsing Cookie header
for Uri '...'"

I'm wondering what is the correct way of doing things?

Thanks!


Regards,

Peter
 
Back
Top