服务有时如何获得SSL / TLS错误

时间:2018-12-03 22:10:59

标签: c# ssl service

我们让此Windows服务每5秒运行一次,以便能够在99%的时间内连接并获取数据。有一些问题尚未解决,服务将开始失败。我们将在几分钟/几小时内将这个错误发送回来,然后该服务似乎会自行修复并继续获取数据。

System.Net.WebException:请求已中止:无法创建SSL / TLS安全通道。    在System.Net.HttpWebRequest.GetResponse()

我想知道下面的代码中是否有任何东西可以产生这种行为。如果没有,我猜这是我们正在ping服务器的问题。任何帮助,将不胜感激。

ServicePointManager.SecurityProtocol.SecurityProtocolType.Tls12;
ServicePointManager.Expect100Continue = false;

public abstract class QueryBase
{
    private const string URL = "https://whatever.com/xml/query";
    private readonly X509Certificate certificate;
    public static Cookie Session { get; set; }
    private readonly Regex sessionReg = new Regex("Session=(\\w+)", RegexOptions.Compiled);
    protected QueryBase(X509Certificate cert)
    {
        certificate = cert;
    }

    protected abstract string GetPostData();

    public string SubmitQuery()
    {
        string data;

        var request = CreateRequest();

        using (var response = (HttpWebResponse) request.GetResponse())
        {
            if (Session == null)
            {
                for (var i = 0; i < response.Headers.Count; i++)
                {
                    var name = response.Headers.GetKey(i);
                    if (name != "Set-Cookie") continue;
                    var value = response.Headers.Get(i);
                    var match = sessionReg.Match(value);
                    if (match.Captures.Count <= 0) continue;
                    Session = new Cookie("Session", match.Groups[1].Value, "/", "whatever.com");
                    break;
                }
            }
            using (var responseStream = response.GetResponseStream())
            {
                using (var reader = new StreamReader(responseStream))
                {
                    data = reader.ReadToEnd();
                }
            }
        }
        return data;
    }

    private HttpWebRequest CreateRequest()
    {
        var request = (HttpWebRequest) WebRequest.Create(URL);
        request.ContentType = "text/xml";
        request.Method = "POST";
        request.UserAgent = "NOTABROWSER";

        request.ClientCertificates.Add(certificate);

        if (Session != null)
        {
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(Session);
        }

        var xml = GetPostData();

        var xmlBytes = Encoding.ASCII.GetBytes(xml);
        request.ContentLength = xmlBytes.Length;

        var s = request.GetRequestStream();
        s.Write(xmlBytes, 0, xmlBytes.Length);

        return request;
    }
}

1 个答案:

答案 0 :(得分:0)

可能是服务器,但可能是客户端证书

“无法创建SSL / TSL安全通道”表示未建立连接。这意味着您不会传输实际的请求,也不会对Cookie进行任何处理。客户证书would be used正在建立连接,因此,如果客户证书由于任何原因而发生更改,就可以。