2016-07-25 101 views
0

返回值此刻我有了這個代碼,以獲得SMTP-服務器的有效期限:C#獲取SMTP-服務器的SSL證書有效期從ServerCertificateValidationCallback

namespace SMTPCert 
{ 
    public class SMTPCert 
    { 
     public static void 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); 
        } 
        catch (Exception) 
        { 
         return; 
        } 
       } 
      } 
     }

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

}

我的問題是,我想將GetSMTPCert方法從void更改爲字符串,以便將證書到期日期返回給我的主方法。 但目前我只能在RemoteServerCertificateValidationCallback方法中獲得到期日期,並且無法從那裏返回。是否有任何可能的方法獲取證書到期日期到我的GetSMTPCert方法,然後將其返回到我的主要方法?

有關其他方式獲取SMTP服務器的SSL證書過期日期的建議也是受歡迎的。

回答

0

好吧我解決了這個問題,通過將類型字符串「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; 
    } 
} 

}

我猜我想有點太複雜了。

相關問題