I am trying to create an XML document from an https web request, but I am having trouble getting it to work when the site has an invalid certificate. I want my application to not care about the certificate, I want it to live it's life on the edge without fear!
Here is the initial code I had, which I have used before may times to get what I want from a standard http (non SSL) request:
XmlDocument xml = new XmlDocument();
XmlTextReader reader = new XmlTextReader("https://www.example.com");
xml.Load(reader);
With the site having an invalid SSL certificate I am now getting the following error:
The request was aborted: Could not create SSL/TLS secure channel.
Now I have done my Google-ing and tried a number of promising solutions but it seems to be of no help.
One I tried here on SO looked good but didn't seem to work, I added the 'accepted answer' line of code directly before my code above as it wasn't too clear as where it should go.
In case it makes any difference, my code is in a class library and I am testing via a console app. I am also using .Net 4.
Here is my latest attempt (which does not work):
XmlDocument xml = new XmlDocument();
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback((s, ce, ch, ssl) => true);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlCommand);
request.Credentials = CredentialCache.DefaultCredentials;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream receiveStream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(receiveStream);
xml.Load(reader);
}
}
OK so I have found the solution. We had opted to try and disable the SSL on the server for testing and noticed it was using SSL 3. After another Google search I found some additional code to fix the issue (important to set the SecurityProtocolType
):
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback((s, ce, ch, ssl) => true);
XmlDocument xml = new XmlDocument();
XmlTextReader reader = new XmlTextReader(urlCommand);
xml.Load(reader);