C# Get xml site over SSL/TLS - https://

时光怂恿深爱的人放手 提交于 2019-12-03 20:31:24

问题


I need to be able to read xml/rss from a https web site in a console program.

until now my program supports plain http, and i've been searching around but i cant seem to find an easy way to implement support for https. It would not matter if the site has a valid certificate or not, but i would appriciate to get hints towards how i would check these certificates to.

I might not know too much about this so any hints are appriciated!

what i currently do for http is:

XmlTextReader rssReader;
XmlDocument rssDoc;
rssReader = new XmlTextReader(url);
rssDoc = new XmlDocument();
rssDoc.Load(rssReader);

When trying this on a site without a trusted certificate i get an error stating: "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

string url = "https://somesite.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();

My program needs to support both trusted and untrusted https sites.

Program is running on a server, and hence has to handle the untrusted https sites in code.


回答1:


For the certificate issue try the following...

ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback((s, ce, ch, ssl) => true);

...somewhere at the start - or before doing the request.

That's basically validating any certificate unconditionally, a bit simplified.

EDIT: that's 'to blindly' trust (and is of global character for your app) - proper implementation would handle the parameters - or entails implementing ICertificatePolicy to specifically deal with different hosts/certificates.

EDIT (certificates): as to how the certificates and SSL actually work - and related to the above (based on the comments/discussion)...

http://www.verisign.com/ssl/ssl-information-center/how-ssl-security-works/index.html
How does SSL really work?
https://superuser.com/questions/84572/public-key-encryption




回答2:


You'll have to send an HttpWebRequest or use HttpClient. Both of which are designed for making/negotiating these connection.

Possible Dupe: How to load xml from https using XmlTextReader

How do I use WebRequest to access an SSL encrypted site using https?

HttpWebRequest with https in C#



来源:https://stackoverflow.com/questions/10036161/c-sharp-get-xml-site-over-ssl-tls-https

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!