?
Solved

Hwo do I resolve a "A connection attempted failed..." exception when using HttpWebRequest?

Posted on 2008-06-11
3
Medium Priority
?
498 Views
Last Modified: 2013-12-17
I've created a site that acts as a proxy for mobile devices for a client's existing site. Everything seems to be working fine but when I deploy the application to the server, after a seemingly random amount of time I am no longer able to log in. I should mention that by "logging in," I am passing my login information to the client's login form and parsing the result to evaluate a successful log in.

I am using a series of HttpWebRequest and HttpWebResponse objects accomplish this. While running my application locally, I never have a problem with this. However when deployed, after a while the application will throw a WebException often with the following inner exception:

"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond (IP address appears here)"

I'm attaching a sample of the code I'm using to accomplish this as well as some details which may or may not be important:

* I am using a cookieless session state.
* I am using HTTPS to communicate with the client but I have tried switching to HTTP and the error still occurs.
* When the error occurs in my application, the client's site is experiencing no errors or delays.
* The server is deployed behind a load balancer.
* The client has informed me that they see nothing out of the ordinary regarding the requests coming from my application.
* Restarting IIS or republishing the application clears the error up immediately. It will eventually begin to occur again though.

I'm wondering if there is an issue with these HttpWebRequests being left open in some way and that perhaps over time they are holding open too many resources. As I stated above, a simple restart of IIS or republishing the application seems to cure this problem temporarily. I have made an extra effort to make sure that I am cleaning up my resources as best I can.

I would appreciate any possible help with this problem. I'm under a very tight time line and this error has sprung up very unexpectedly. Thank you.

PS: Also, in case this comes up, I added the following to the Web.Config file based on another suggestion:

<system.net>
  <defaultProxy>
    <proxy usesystemdefault="False" />
  </defaultProxy>
</system.net>

It has had no effect.
// *** The following is a sample of the call I'm making to the method below that throws the exception.
 
string loginVars = "email=" + Server.UrlEncode(txtEmail.Text.Trim()) + "&password=" + Server.UrlEncode(txtPassword.Text);
 
CookieContainer cc = new CookieContainer();
 
// This call throws the exception.
PageResponse resp = GetPageResponse("http://www.clientsite.com/Login", loginVars, RequestType.POST, cc, false, "MSIE 7.0");
 
// *** End Sample.
 
protected PageResponse GetPageResponse(string url, string pageVariables, RequestType requestType, CookieContainer cookieContainer,
            bool allowAutoRedirect, string userAgent)
        {
            PageResponse response = new PageResponse();
            HttpWebRequest req = null;
            Stream s = null;
 
            if (cookieContainer == null)
                cookieContainer = new CookieContainer();
 
            if (requestType == RequestType.GET)
            {
                if (pageVariables != null && pageVariables.Length > 0)
                    pageVariables = "?" + pageVariables;
                else
                    pageVariables = "";
 
                req = (HttpWebRequest)WebRequest.Create(url + pageVariables);
                req.CookieContainer = cookieContainer;
                req.Method = "GET";
            }
            else
            {
                req = (HttpWebRequest)WebRequest.Create(url);
                req.CookieContainer = cookieContainer;
                req.Method = "POST";
            }
 
            
 
            req.AllowAutoRedirect = allowAutoRedirect;
            req.KeepAlive = false;
            req.UserAgent = userAgent;
 
            if (requestType == RequestType.POST)
            {
                ASCIIEncoding enc = new ASCIIEncoding();
                byte[] outData = enc.GetBytes(pageVariables);
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = outData.Length;
 
                s = req.GetRequestStream();
                s.Write(outData, 0, outData.Length);
 
                if (s != null)
                {
                    try { s.Close(); }
                    catch (Exception) { }
                    s = null;
                }
            }
 
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
 
            using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
            {
                response.Content = sr.ReadToEnd();
            }
 
            response.ResponseURI = resp.ResponseUri.ToString();
            response.StatusCode = resp.StatusCode;
            response.Cookies = resp.Cookies;
 
            if (resp.Headers["Location"] != null)
                response.RoutingLocation = resp.Headers["Location"];
            else
                response.RoutingLocation = "";
 
            if (resp != null)
            {
                try
                {
                    resp.Close();
                }
                catch (Exception) { }
 
                resp = null;
            }
 
            req = null;
            
            return response;
 
        }
 
        protected class PageResponse
        {
            public string Content { get; set; }
            public HttpStatusCode StatusCode { get; set; }
            public string ResponseURI { get; set; }
            public string RoutingLocation { get; set; }
            public CookieCollection Cookies { get; set; }
        }
 
        protected enum RequestType
        {
            GET = 0,
            POST = 1
        };

Open in new window

0
Comment
Question by:Samriv
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 33

Expert Comment

by:raterus
ID: 21761869
Take a look at this code you have, you have a couple of places where this occurs.

                try
                {
                    resp.Close();
                }
                catch (Exception) { }


Do you realize you are telling .Net to completely ignore the error?  This is likely a very dangerous and bad idea.  I would take out the try/catch in this place and let the exception be raised, then you will probably see what is going on.
0
 

Author Comment

by:Samriv
ID: 21761972
Yes, I'd figured I'd take the time to add some handling for it in the future. Unfortunately the timeout error I'm experiencing began even before I put in the call to Close. I'll remove the try-catch but I don't think the original exception is occurring here.
0
 

Accepted Solution

by:
Samriv earned 0 total points
ID: 21807570
I ended up porting this code over to a Java web service using HttpClient and calling it from the web application. The web service never experiences this problem so perhaps it's a bug in the .NET framework.
0

Featured Post

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

719 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question