C# WebRequest非常慢
我的方法如下所示:C# WebRequest非常慢,c#,.net,httpwebrequest,C#,.net,Httpwebrequest,我的方法如下所示: public string Request(string action, NameValueCollection parameters, uint? timeoutInSeconds = null) { parameters = parameters ?? new NameValueCollection(); ProvideCredentialsFor(ref parameters); var data = parameters.ToUrlParam
public string Request(string action, NameValueCollection parameters, uint? timeoutInSeconds = null)
{
parameters = parameters ?? new NameValueCollection();
ProvideCredentialsFor(ref parameters);
var data = parameters.ToUrlParams(); // my extension method converts the collection to a string, works well
byte[] dataStream = Encoding.UTF8.GetBytes(data);
string request = ServiceUrl + action;
var webRequest = (HttpWebRequest)WebRequest.Create(request);
webRequest.AllowAutoRedirect = false;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
webRequest.Timeout = (int)(timeoutInSeconds == null ? DefaultTimeoutMs : timeoutInSeconds * 1000);
webRequest.Proxy = null; // should make it faster...
using (var newStream = webRequest.GetRequestStream())
{
newStream.Write(dataStream, 0, dataStream.Length);
}
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string uri = webResponse.Headers["Location"];
string result;
using (var sr = new StreamReader(webResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
服务器发送JSON作为响应。它适用于小JSON,但当我请求一个大JSON时,会出现一些问题。我所说的大型浏览器是指需要1-2分钟才能在浏览器中显示的东西(谷歌浏览器,包括服务器端生成时间)。它实际上是412KB的文本。当我尝试使用上述方法请求相同的JSON时,我得到一个web异常(超时)。我将超时时间改为10分钟(至少比chrome长5倍)。还是一样
有什么想法吗
编辑
这似乎与MS技术有关。在IE上,此JSON也不会加载。请确保关闭请求。否则,一旦达到允许的最大连接数(对我来说,有一次低至4个),就必须等待较早的连接超时。最好使用
using (var response = webRequest.GetResponse()) {...