System.Net.WebException. The Underlying Connection

1829阅读 0评论2011-07-08 meteorm
分类:WINDOWS

PRB: "System.Net.WebException. The Underlying Connection Was Closed. Could Not Establish Trust Relationship with Remote Server." Error Message When You Upgrade the .NET Framework

To work around this problem, you can implement ICertificatePolicy. Then you must pass ICertificatePolicy to ServicePointManager.CertificatePolicy before the Web Service method call is made.

The following code sample is implemented in the client application. The code forces the client application to accept every certificate that the server provides. This method weakens the security of the application because the authentication of the server is bypassed. To safely work around this problem, make sure that the certificate of the server contains the expected name before you allow the connection to continue.

The following sample code implements ICertificatePolicy and then accepts every request under SSL:

Microsoft Visual Basic .NET

Import the following two namespaces, and then implement the class:

Imports System.Net
Imports System.Security.Cryptography.X509Certificates
Public Class MyPolicy
  Implements ICertificatePolicy

  Public Function CheckValidationResult(ByVal srvPoint As ServicePoint, _
                ByVal cert As X509Certificate, ByVal request As WebRequest, _
                ByVal certificateProblem As Integer) _
            As Boolean Implements ICertificatePolicy.CheckValidationResult
    'Return True to force the certificate to be accepted.
    Return True
  End Function
End Class
Microsoft Visual C# .NET

Import the following two namespaces, and then implement the class:
using System.Net;
using System.Security.Cryptography.X509Certificates;

public class MyPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
          ServicePoint srvPoint
        , X509Certificate certificate
        , WebRequest request
        , int certificateProblem) {

        //Return True to force the certificate to be accepted.
        return true;

    } // end CheckValidationResult
} // class MyPolicy
Include the following code in the client code. Before you make the Web Service method call from the client code, the following statement (in either Visual Basic .NET or Visual C# .NET, as appropriate) must be executed:

Visual Basic .NET
System.Net.ServicePointManager.CertificatePolicy = New MyPolicy()
Visual C# .NET
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
上一篇:Consuming Webservices over HTTPS (SSL)-.NET教程,Web
下一篇:批处理 命令返回结果到变量示例