我收到“底层连接已关闭:连接意外关闭”。尝试在生产服务器上使用 HttpWebRequest 类进行 POST 时出错,但在我的开发计算机上它工作正常。
我最初尝试使用 WebClient 类,但我切换到 HttpWebRequest 来尝试研究问题时发现的一些建议(例如将 KeepAlive 设置为 false、PreAuthenticate true
和协议版本为 1.0)。
由于它只发生在生产服务器上,我猜测它可能与 IIS 有关。
这是我的代码
HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequest.Create(webURL);
ASCIIEncoding encoding=new ASCIIEncoding();
Byte[] postbytes = Encoding.ASCII.GetBytes(data);
HttpWReq.Headers.Add("Authorization",
String.Format("Basic {0}", authstring));
HttpWReq.KeepAlive = false;
HttpWReq.PreAuthenticate = true;
HttpWReq.Credentials = CredentialCache.DefaultCredentials;
HttpWReq.UseDefaultCredentials = true;
HttpWReq.ProtocolVersion = HttpVersion.Version10;
HttpWReq.Method = "POST";
HttpWReq.ContentType = "application/x-www-form-urlencoded";
HttpWReq.ContentLength = postbytes.Length;
Stream newStream = HttpWReq.GetRequestStream();
newStream.Write(postbytes, 0, postbytes.Length);
newStream.Close();
我最初尝试使用 WebClient 类的代码
/* WebClient client = new WebClient();
client.Headers.Add("Authorization",
String.Format("Basic {0}", authstring));
client.Headers.Add("Content-Type",
"application/x-www-form-urlencoded");
client.UseDefaultCredentials = true;
System.Net.ServicePointManager.Expect100Continue = false;
Byte[] postbytes = Encoding.ASCII.GetBytes(data);
byte[] resp = client.UploadData(webURL, "POST", postbytes); */
谢谢,任何帮助将不胜感激。
EDIT:
使用 fidler 检查标头我得到了这个信息
POST [MyWebSite] HTTP/1.1
Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave- flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*
Referer: [MyWebSite]
Accept-Language: en-us
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; GTB6.5; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: [MyHost]
Content-Length: 188
Connection: Keep-Alive
Pragma: no-cache
Cookie: __utma=62854692.1254171006.1276438746.1289273298.1289317993.21; __utmz=62854692.1277743505.3.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=yeled; ASPSESSIONIDQQQRCRAT=ANNHGGNBNOFNFCLHPBEJIMLC
__VIEWSTATE=%2FwEPDwUKMjA0OTM4MTAwNGRktZi0IsIUo6MOCYTxun8p8Po4AWeTtipGZ4L9%2FkY3KZU%3D&__EVENTVALIDATION=%2FwEWAgLHhsXtBwK14deQBbiFCpWBnsp%2BicqBy%2FNXAkhuVDX9WF1jZayRuTgPc3Ov&btnTest=Test
EDIT2
如果将目标框架(我使用一个新项目进行测试)设置为 2.0(我没有测试框架的每个版本),它就可以工作。我猜测 .net 在 .net 4.0 中以不同的方式处理安全性。这不是一个解决方案,但我希望有人可以使用该信息来帮助我解决这个问题。