加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 通过HTTPS消费Web服务时抛出的System.Net.WebException

发布时间:2020-12-15 06:34:10 所属栏目:百科 来源:网络整理
导读:当使用HTTPS对服务器上运行的Web服务进行调用时,我的应用程序会抛出一个System.Net.WebException消息“底层连接已关闭:无法与远程服务器建立信任关系”.我不知道如何解决这个问题,并成功打电话. 解决方法 经过一番研究,我发现了一个 Jan Tielens的博客文章,
当使用HTTPS对服务器上运行的Web服务进行调用时,我的应用程序会抛出一个System.Net.WebException消息“底层连接已关闭:无法与远程服务器建立信任关系”.我不知道如何解决这个问题,并成功打电话.

解决方法

经过一番研究,我发现了一个 Jan Tielens的博客文章,解释了发生了什么,并解决了我的问题:

When you browse to a HTTPS site,you probably get a dialog window asking you if you want to trust the certificate provided by the webserver. So the responsibility of accepting the certificate is handled by the user. Let’s get back to the webservice scenario,if you want to invoke a webservice located on a webserver which uses SSL and HTTPS there is a problem. When you make the call from code,there is no dialog window popping up,and asking if you trust the certificate (luckily because this would be pretty ugly in server-side scenarios); probably you’ll get following exception:

An unhandled exception of type System.Net.WebException occurred in System.dll
Additional information: The underlying
connection was closed: Could not
establish trust relationship with
remote server.


但是有一个解决方案
你可以解决这个问题
代码创建自己的
CertificatePolicy类(其中
实现ICertificatePolicy
接口).在这个班上你会的
必须自己写
CheckValidationResult函数
必须像你一样返回真或假
会在对话框中按是或否
窗口.为了发展目的,我已经
创建了以下类
接受所有证书,所以你不会
得到令人讨厌的WebException:

public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
    public TrustAllCertificatePolicy() { }

    public bool CheckValidationResult(ServicePoint sp,X509Certificate cert,WebRequest req,int problem)
    {
        return true;
    }
}

As you can see the
CheckValidationResult function always
returns true,so all certificates will
be trusted. If you want to make this
class a little bit more secure,you
can add additional checks using the
X509Certificate parameter for example.
To use this CertificatePolicy,you’ll
have to tell the ServicePointManager
to use it:

System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

This must be done (one time during the application life cycle) before making the call to your webservice.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读