SSL certificate pre-fetch .NET

后端 未结 1 1925
孤独总比滥情好
孤独总比滥情好 2021-02-02 01:02

I am writing a utility that would allow me to monitor the health of our websites. This consists of a series of validation tasks that I can run against a web application. One o

1条回答
  •  野的像风
    2021-02-02 01:36

    I've just tried this, which "works on my machine (tm)".

    It returns the text string representing the expiry date on the server's certificate, and requires an actual hit to be made on the web site.

    private string GetSSLExpiryDate(string url)
    {
        Uri u = new Uri(url);
        ServicePoint sp = ServicePointManager.FindServicePoint(u);
    
        string groupName = Guid.NewGuid().ToString();
        HttpWebRequest req = HttpWebRequest.Create(u) as HttpWebRequest;
        req.ConnectionGroupName = groupName;
    
        using (WebResponse resp = req.GetResponse())
        {
            // Ignore response, and close the response.
        }
        sp.CloseConnectionGroup(groupName);
    
        // Implement favourite null check pattern here on sp.Certificate
        string expiryDate = sp.Certificate.GetExpirationDateString();
    
        return expiryDate;
    }
    

    I'm afraid I don't know all the rights and wrongs of using ServicePoint, and any other hoops that you might need to jump through, but you do get an SSL expiry date for the actual web site you want to know about.

    EDIT: ensure the "url" parameter use the https:// protocol.

    e.g. string contosoExpiry = GetSSLExpiryData("https://www.contoso.com/");

    0 讨论(0)
提交回复
热议问题