RemoteCertificateValidationCallback 委托

定义

验证用于身份验证的远程安全套接字层 (SSL) 证书。

C#
public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors);
C#
public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors);

参数

sender
Object

一个对象,它包含此验证的状态信息。

certificate
X509Certificate

用于对远程方进行身份验证的证书。

chain
X509Chain

与远程证书关联的证书颁发机构链。

sslPolicyErrors
SslPolicyErrors

与远程证书关联的一个或多个错误。

返回值

Boolean 值,它确定是否接受指定证书进行身份验证。

示例

下面的代码示例实现由 类的 RemoteCertificateValidationCallback 实例调用的方法。 如果存在验证错误,此方法将显示这些错误并返回 false,这会阻止与未经身份验证的服务器通信。

C#

// The following method is invoked by the RemoteCertificateValidationDelegate.
public static bool ValidateServerCertificate(
      object sender,
      X509Certificate certificate,
      X509Chain chain,
      SslPolicyErrors sslPolicyErrors)
{
   if (sslPolicyErrors == SslPolicyErrors.None)
        return true;

    Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

    // Do not allow this client to communicate with unauthenticated servers.
    return false;
}

下面的代码示例使用前面的代码示例中定义的 方法创建委托。

C#
// Create a TCP/IP client socket.
// machineName is the host running the server application.
TcpClient client = new TcpClient(machineName,5000);
Console.WriteLine("Client connected.");
// Create an SSL stream that will close the client's stream.
SslStream sslStream = new SslStream(
    client.GetStream(),
    false,
    new RemoteCertificateValidationCallback (ValidateServerCertificate),
    null
    );
// The server name must match the name on the server certificate.
try
{
    sslStream.AuthenticateAsClient(serverName);
}
catch (AuthenticationException e)
{
    Console.WriteLine("Exception: {0}", e.Message);
    if (e.InnerException != null)
    {
        Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
    }
    Console.WriteLine ("Authentication failed - closing the connection.");
    client.Close();
    return;
}

注解

委托的 sslPolicyErrors 参数包含对客户端或服务器进行身份验证时 SSPI 返回的任何证书错误。 此 Boolean 委托调用的方法返回的值确定是否允许身份验证成功。

此委托与 类一 SslStream 起使用。

扩展方法

GetMethodInfo(Delegate)

获取指示指定委托表示的方法的对象。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

另请参阅