我们的环境有多个 Web 服务器在负载均衡器后面运行。如果我修改我的主机文件以直接转到将绕过负载平衡器的 Web 服务器,则 HttpWebRequest 工作正常。如果我删除我的主机文件中的条目并让请求通过负载平衡器,它会返回 404。但是,如果我在同一台计算机上使用简单的 .html 文件执行相同的请求,我将从它运行 HttpWebRequest 一切正常我的主机文件中是否有条目。
任何想法为什么它可以通过浏览器(Chrome)使用html文件而不是HttpWebRequest?
该请求是一个 POST 请求,它上传一个文件和 3 个其他参数。
提前感谢您的任何想法。
编辑:我尝试将我的 UserAgent 设置Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1
为 Chrome 在使用 html 文件时发送的内容。
这是我正在使用的功能,目前在没有负载平衡器的情况下有效:
private void PostFileToWebServer(byte[] file)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
var request = (HttpWebRequest)WebRequest.Create(_url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
//Time in milliseconds
request.Timeout = 1200000;
request.Host = "ourdomain.com";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1";
request.CookieContainer = new CookieContainer(100000);
var memStream = new MemoryStream();
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
string formDataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach(var key in _parameters.AllKeys)
{
string formData = string.Format(formDataTemplate, key, _parameters[key]);
byte[] formDataBytes = Encoding.UTF8.GetBytes(formData);
memStream.Write(formDataBytes, 0, formDataBytes.Length);
memStream.Write(boundarybytes, 0, boundarybytes.Length);
}
string header = string.Format("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n Content-Type: application/octet-stream\r\n\r\n", _fileName);
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
memStream.Write(headerBytes, 0, headerBytes.Length);
memStream.Write(file, 0, file.Length);
memStream.Write(boundarybytes, 0, boundarybytes.Length);
request.ContentLength = memStream.Length;
Stream requestStream = request.GetRequestStream();
memStream.Position = 0;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
var response = request.GetResponse();
Stream stream2 = response.GetResponseStream();
var reader2 = new StreamReader(stream2);
System.Diagnostics.Debug.WriteLine(reader2.ReadToEnd());
response.Close();
}
编辑:我注释掉了request.ContentType = "multipart/form-data; boundary=" + boundary;
,它适用于负载均衡器。有人对此有解释吗?