Search code examples
c#asp.net-mvchttpwebrequest

HttpWebRequest is very slow without proxy


I wrote this code to read data from an external url.

request.GetResponse() takes more than a minute to run and is very slow.

string responseContent;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://payroll/PayrollReport/getPaymentHistory?number=13990701&reason=21&username=8062122&Credential=E5ohh/BZDBWAQBE2R8tmbUSiVGJ2/ndI3AmqDiCMBylOIK/eAdRZog==");
request.Method = "GET";
request.Proxy = GlobalProxySelection.GetEmptyWebProxy(); // null;
System.Net.ServicePointManager.Expect100Continue = false;
ServicePointManager.UseNagleAlgorithm = false;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (Stream responseStream = response.GetResponseStream())
    {
        using (StreamReader sr = new StreamReader(responseStream))
            responseContent = sr.ReadToEnd();
    }
}

But when call this url with post man is very fast and run less than 1000ms.

enter image description here

In network capture only location property is different between c# and post man

enter image description here enter image description here enter image description here

Please help me slow down code execution


Solution

  • I added AspxAutoDetectCookieSupport=1 to the code and the problem was solved.

    The AspxAutoDetectCookieSupport=1 querystring is added automatically by ASP.NET during the cookie support detection phase. Since cookieless attribute in the web.config file is set to "AutoDetect", the ASP.NET runtime tries to detect whether the user's browser supports cookies, and the querystring parameter is added during that process. If cookies are supported, the Session ID is kept in a cookie, and if not the Session ID is sent in the Url of all future requests by that user.

    Uri target = new Uri("http://payroll/PayrollReport/getPaymentHistory?number=13990701&reason=21&username=8062122&Credential=E5ohh/BZDBWAQBE2R8tmbUSiVGJ2/ndI3AmqDiCMBylOIK/eAdRZog==");
    
    string responseContent;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(target);
    
    request.CookieContainer = new CookieContainer();         
    request.CookieContainer.Add(new Cookie("AspxAutoDetectCookieSupport", "1") { Domain = target.Host });
    
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (Stream responseStream = response.GetResponseStream())
        {
            using (StreamReader sr = new StreamReader(responseStream))
                responseContent = sr.ReadToEnd();
        }
    }