RemoteCertificateValidationCallback 代理人

定義

驗證用於驗證的遠端 Secure Sockets Layer (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

另請參閱