目前,我已获得以下代码来获取SMTP服务器的到期日期:

命名空间SMTPCert
{
    公共类SMTPCert
    {
        公共静态无效GetSMTPCert(字符串ServerName)
        {
            ServicePointManager.ServerCertificateValidationCallback =新的RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
            使用(System.Net.Mail.SmtpClient S =新的System.Net.Mail.SmtpClient(ServerName))
            {
                S.EnableSsl = true;
                使用(System.Net.Mail.MailMessage M =新的System.Net.Mail.MailMessage(“ [email protected]”,“ [email protected]”,“ Test”,“ Test”))
                {
                    尝试
                    {
                        S.Send(M);
                    }
                    捕获(异常)
                    {
                        返回;
                    }
                }
            }
        }

private static bool RemoteServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Console.WriteLine(certificate); return true; }}

}


我的问题是我想将GetSMTPCert方法从void更改为可以将证书到期日期返回给我的main方法的字符串。
但是目前,我只能在RemoteServerCertificateValidationCallback方法中获取到期日期,并且无法从那里返回它。有什么办法可以将证书的到期日期获取到我的GetSMTPCert方法,然后将其返回到我的主方法?

也欢迎提出其他方法来获取SMTP服务器的SSL证书到期日期。

最佳答案

好的,我通过将类型字符串“ CertificateDaysLeft”的公共静态字段添加到我的SMTPCert类中解决了该问题。

namespace SMTPCert
{
    public static string CertificateDaysLeft;

    public static string GetSMTPCert(string ServerName)
    {
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
        using (System.Net.Mail.SmtpClient S = new System.Net.Mail.SmtpClient(ServerName))
        {
            S.EnableSsl = true;
            using (System.Net.Mail.MailMessage M = new System.Net.Mail.MailMessage("[email protected]", "[email protected]", "Test", "Test"))
            {
                try
                {
                    S.Send(M);
                    string daysLeft = CertificateDaysLeft;
                    return daysLeft;
                }
                catch (Exception)
                {
                    string daysLeft = CertificateDaysLeft;
                    return daysLeft;
                }
            }
        }
    }

    private static bool RemoteServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        DateTime ExpirDate = Convert.ToDateTime(certificate.GetExpirationDateString());
        string DaysLeft = Convert.ToString((ExpirDate - DateTime.Today).Days);
        CertificateDaysLeft = DaysLeft;
        Console.WriteLine(certificate);
        return true;
    }
}


}

我想我觉得有点太复杂了。

10-06 14:13