【问题标题】:WebRequest handshake fails due to unexpected packet format由于意外的数据包格式,WebRequest 握手失败
【发布时间】:2013-04-17 18:23:33
【问题描述】:

我有许多 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();
    }

此代码已经运行了很长时间(几个月,超过半年)。从这个周末开始,它开始经常失败(我估计有 90% 的时间,但不是 100% 的时间)。我一直看到的错误是:System.Net.WebException:底层连接已关闭:发送时发生意外错误。 ---> System.IO.IOException: 由于意外的数据包格式,握手失败。 堆栈跟踪如下:

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 - wireshark.org
  • 1.你在代理或防火墙后面吗? 2. 可以用 Fiddler 来嗅探两台服务器之间的数据包请求吗?
  • 1.我不知道,我说的是在网络服务器(我租用的)上运行此代码,所以我假设涉及防火墙。我没有足够的权限访问服务器(除了 Web 控制面板),所以我无法检查(不过我可以寻求支持)。 2. 我不知道如何使用 Fiddler,我已经尝试了几次,但没有任何结果,尤其是我无法控制的两台服务器之间的通信。

标签: asp.net webrequest handshake webexception


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-12-25
    • 2011-07-07
    • 2021-10-27
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    相关资源
    最近更新 更多