Chad

Chad

  • NA
  • 5
  • 6.3k

HttpWebRequest to https server works in fiddler but NOT from Visual Studio

Apr 15 2011 9:59 AM

Here is the scenario. I have written code use a digital certificate to GET cookies from a secured url, to in turn POST data back to another url using the retrieved cookies and same digital certificate. The GET works and cookies are retrieved, the POST comes back with an error 500. I installed fiddler to see what was going on...POST looks fine...cookies are present. I used the feature in fiddler that allows creating a request via drag and drop. POST the exact same POST recorded from C# code that was recorded in fiddler and it works!

What is Fiddler doing that Visual Studio is not? It must be doing something if fiddler can POST the data but Visual Studio returns an error 500. Here is the code below:

        X509Certificate cert = new X509Certificate("mycert.pfx", "certpassword"); 
       
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://servertoGETcookies/fileUpload.html"); 
        req
.CookieContainer = new CookieContainer(); 
        req
.Method = "GET"; 
        req
.ClientCertificates.Add(cert); 
 
       
HttpWebResponse Response = (HttpWebResponse)req.GetResponse(); 
       
CookieCollection ck = req.CookieContainer.GetCookies(req.RequestUri); 
       
string strcookie = ck[0].Value; 
       
string strcookie2 = ck[1].Value; 
       
Response.Close(); 
 
        req
= (HttpWebRequest)WebRequest.Create("https://servertoPOSTdatawithcookies/main"); 
        req
.CookieContainer = new CookieContainer(); 
       
Cookie auth = new Cookie("_wl_authcookie_", strcookie2); 
       
Cookie jsess = new Cookie("JSESSIONID", strcookie); 
        auth
.Domain = "server"; 
        jsess
.Domain = "server"; 
        req
.CookieContainer.Add(auth); 
        req
.CookieContainer.Add(jsess); 
        req
.ClientCertificates.Add(cert); 
        req
.Method = "POST"; 
 
       
Byte[] data = ReadByteArrayFromFile("filewithdatatoPOST.txt"); 
        req
.ContentLength = data.Length; 
       
Stream myStream = req.GetRequestStream(); 
        myStream
.Write(data, 0, data.Length); 
        myStream
.Close(); 
 
       
HttpWebResponse Response2 = (HttpWebResponse)req.GetResponse(); 
       
Stream strm = Response2.GetResponseStream(); 
       
StreamReader sr2 = new StreamReader(strm); 
       
Response2.Close(); 


Answers (4)