Asp.net 由于意外的数据包格式,WebRequest握手失败

Asp.net 由于意外的数据包格式,WebRequest握手失败,asp.net,webrequest,handshake,webexception,Asp.net,Webrequest,Handshake,Webexception,我有许多ASP.NET网站和一个Web服务,它们使用相同的代码“登录”到第三方网站。这基本上包括使用WebRequest使用我的凭据向网站的登录页面发送HTTP POST,将生成的cookie存储在CookieContainer中,并在任何后续WebRequest中使用CookieContainer来授权我的网站访问第三方网站上的页面 代码基本如下: public LoginResults Login() { // Create the webrequest

我有许多ASP.NET网站和一个Web服务,它们使用相同的代码“登录”到第三方网站。这基本上包括使用WebRequest使用我的凭据向网站的登录页面发送HTTP POST,将生成的cookie存储在CookieContainer中,并在任何后续WebRequest中使用CookieContainer来授权我的网站访问第三方网站上的页面

代码基本如下:

    public LoginResults Login()
    {
        // Create the webrequest
        var request = CreateInitialWebRequest(LOGIN_URL);
        request.AllowAutoRedirect = false;

        // Set the cookiecontainer, which will be filled with the authentication cookies
        this.cookieContainer = new CookieContainer();
        request.CookieContainer = this.cookieContainer;

        // Set the username and pw in a HTTP POST call
        SetPostContent(request, string.Format(LOGIN_PARAMETERS, this.Username, this.Password));

        // Read the response
        using (var httpWebResponse = (HttpWebResponse)request.GetResponse())
        {
            using (var responseStream = httpWebResponse.GetResponseStream())
            {
                 // Omitted:
                 // read response and determine if login was successful
            } 
        }
    }

    private HttpWebRequest CreateInitialWebRequest(string uri)
    {
        var request = (HttpWebRequest)WebRequest.Create(uri);
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        return request;
    }

    private HttpWebRequest CreateWebRequest(string uri)
    {
        var request = this.CreateInitialWebRequest(uri);
        request.CookieContainer = cookieContainer;
        request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, */*";
        request.UserAgent = "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";
        request.Method = "GET";
        request.Timeout = 10000; // 10 sec
        return request;
    }

    private static void SetPostContent(HttpWebRequest req, string postData)
    {
        req.Method = "POST";
        byte[] bytes = new ASCIIEncoding().GetBytes(postData);
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = (long)bytes.Length;
        ((WebRequest)req).GetRequestStream().Write(bytes, 0, bytes.Length);
        ((WebRequest)req).GetRequestStream().Close();
    }
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: The handshake failed due to an unexpected packet format.
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.TlsStream.CallProcessAuthentication(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at iRacingForumService.HttpPost.SetPostContent(HttpWebRequest req, String postData)
at iRacingForumService.HttpPost.Login()
此代码已经运行了很长时间(几个月,半年多)。从这个周末开始,它经常失败(我估计90%的时间失败,但不是100%的时间失败)。我一直看到的错误是:System.Net.WebException:基础连接已关闭:发送时发生意外错误。-->System.IO.IOException:由于意外的数据包格式,握手失败。 堆栈跟踪如下所示:

    public LoginResults Login()
    {
        // Create the webrequest
        var request = CreateInitialWebRequest(LOGIN_URL);
        request.AllowAutoRedirect = false;

        // Set the cookiecontainer, which will be filled with the authentication cookies
        this.cookieContainer = new CookieContainer();
        request.CookieContainer = this.cookieContainer;

        // Set the username and pw in a HTTP POST call
        SetPostContent(request, string.Format(LOGIN_PARAMETERS, this.Username, this.Password));

        // Read the response
        using (var httpWebResponse = (HttpWebResponse)request.GetResponse())
        {
            using (var responseStream = httpWebResponse.GetResponseStream())
            {
                 // Omitted:
                 // read response and determine if login was successful
            } 
        }
    }

    private HttpWebRequest CreateInitialWebRequest(string uri)
    {
        var request = (HttpWebRequest)WebRequest.Create(uri);
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        return request;
    }

    private HttpWebRequest CreateWebRequest(string uri)
    {
        var request = this.CreateInitialWebRequest(uri);
        request.CookieContainer = cookieContainer;
        request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, */*";
        request.UserAgent = "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";
        request.Method = "GET";
        request.Timeout = 10000; // 10 sec
        return request;
    }

    private static void SetPostContent(HttpWebRequest req, string postData)
    {
        req.Method = "POST";
        byte[] bytes = new ASCIIEncoding().GetBytes(postData);
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = (long)bytes.Length;
        ((WebRequest)req).GetRequestStream().Write(bytes, 0, bytes.Length);
        ((WebRequest)req).GetRequestStream().Close();
    }
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: The handshake failed due to an unexpected packet format.
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.TlsStream.CallProcessAuthentication(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at iRacingForumService.HttpPost.SetPostContent(HttpWebRequest req, String postData)
at iRacingForumService.HttpPost.Login()
当我搜索这个错误时,我一直看到的唯一解决方案是禁用WebRequest的KeepAlive属性和/或将ProtocolVersion设置为HttpVersion10。我尝试了这两种方法(每种可能的组合),但没有任何帮助

错误并不总是出现,但当它出现时,我可以继续尝试所有我喜欢的,我会一次又一次地得到错误。如果我让它保持几分钟,然后再试一次,我有机会它会工作(一旦它工作了,它会继续工作一段时间)

奇怪的是,我没有改变任何事情;这段代码已经运行了几个月,没有出现任何问题。完全有可能第三方网站改变了某些内容,和/或我的网络主机提供商改变了某些内容。但为了以防万一,我可以做些什么来解决这个问题,我想问一下我是否做错了什么

我可以联系第三方网站(可能不会得到回复)或我的网络主机,但我需要更好地了解到底出了什么问题,因为仅仅把这个错误扔给他们可能对他们没有帮助

那么,我能做些什么吗?或者,我突然在我所有的网站上看到这个错误(它们都连接到同一个第三方网站)有什么好的原因吗


谢谢

由于这种情况是间歇性发生的,您可能需要联系服务器管理员,了解情况。服务器可能会因为负载、配置错误或其他一些网络问题而拒绝或关闭连接。

尝试使用嗅探器(如Wireshark-)1解决此问题。你是在代理还是防火墙后面?2.您能否使用Fiddler嗅探两台服务器之间的数据包请求?1。我不知道,我说的是在Web服务器(我租的)上运行这段代码,所以我假设其中涉及到防火墙。我没有足够的权限访问服务器(除了web控制面板),因此无法进行检查(尽管我可以请求支持)。2.我不知道如何使用Fiddler,我已经试过几次了,但都没有结果,特别是在我无法控制的两台服务器之间的通信。