.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

HttpWebRequest: Handling of Broken or Closed TCP Connections

Posted By:      Posted Date: October 23, 2010    Points: 0   Category :.NET Framework
I am wondering whether there is a way to handle broken (or better: closed) TCP connections that reside in the connection pool (ServicePoint) used by a HttpWebRequest instance. What I have seen on Windows 2003 Server systems is that under certain circumstances, all sockets used to connect to a web service are in CLOSE_WAIT state and all subsequent HttpWebRequests fail with a timeout, no new connections to the web service were opened. Looking at the problem with WireShark, I couldn't see any HTTP traffic even though the application kept on making requests that all ended in a timeout.

I have tried to reproduce this behaviour on a development system by writing a simple HTTP server that closes the socket after it has sent a proper HTTP 1.1 response. If you do this, you will see the same behavior that I have described above. Of course, HTTP 1.1 assumes that by default connections are kept alive unless the server explicitly sends a "Connection: Close" header. Thus, the client-side would assume that the connection should be kept alive although the server (that does not function according to HTTP 1.1) already closed it. What stuns me is that the HttpWebRequest, or more specifically the ServicePoint does not recover from such a situation (on Windows Vista/2003 Server the client-side sockets stay in CLOSE_WAIT until they're killed by the OS, on another development m

View Complete Post

More Related Resource Links

Cant reuse Http connections. No KeepAlive header. HttpWebRequest.KeepAlive = true;


I tried to reuse Http connections setting KeepAlive but it simply doesnt work. I looked in the Http messages using Feedler and Charles but all I can see is Connection: close in response. I am sure I use HTTP 1.1 as it says so in the request.

I see 600 TCP connections in wait state opened by 10 threads. Each thread run one http request at a time.

There is also bunch of responses which say - the unauthenticated request. The service requires digest authentication. Why some requestes fail to be authenticated?? 

P.S. I just found this thread: http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/87bc7029-ce23-438a-a767-f7c32dcc63a7 and I tried to set UnsafeAuthenticatedConnectionSharing = true but still my TCP connections are not reused.

    static void GetRest(string rest) 

HttpWebRequest & CookieContainer broken design & implementation


I've spend several months working with HttpWebRequest & CookieContainer, and simply had a miserable time making it work.

My question is whether there's a better approach/workaround to it, and if not hopefully these bugs will be fixed by next 'patch'.

Issue #1.  HttpWebRequest does not setCookies for redirects until the end of redirect.

Suppose you have a scenario where you log in, gets a 302 redirect with a SetCookie header.  Now, the new redirected page verifies that the cookie is set before sending the correct response.  Using HttpWebRequest & CookieContainer, the second redirect request does not have the cookie that response #1 specified, and thus you can never log in using these APIs. 

The only workaround I found so far is to manually do the redirects myself.  This is simply inefficient and no reason why HttpWebRequest should not do this set cookie automatically between redirects.

This kind of redirect scenario happens quite often.  I bet even some of Microsoft's own webpage does this.


Issue #2.  Cannot remove cookies from cookie container.

This doesn't really need explanation.  Why would it not let me remove a cookie?  The only silly approach is to make a new one and copy/add all the cookies except the one you want to remove.  Setting a null value does not remove it either.



Every self-respected programmer should include exception handling techniques. Sometimes your application will generate an error. Regardless of who was responsible for this error, the programmer or the user, it is up to the first to include the necessary exception handling techniques to keep his/her program from crashing. The .Net environment provides useful techniques for avoiding disastrous errors such as try-catch statements and user-defined exceptions.

Global Exception Handling with ASP.NET

After your global exception handler has done its work, you'll want to redirect the users of your website to a friendly page that tells them that something has gone wrong, and then provide them with customer support information as well as a link back to your web application's home page.

SQL Server 2005 Try and Catch Exception Handling

I'm pretty excited to see that there is some real error handling for T-SQL code in SQL Server 2005. It's pretty painful to have your wonderfully architected .NET solution tainted by less-than-VBScript error handling for stored procedures in the database. The big difference being the addition of TRY..CATCH blocks. Let's take a look:

Handling 404 page not found with Error page



      How do i handle 404 page not found?

Error while using exception handling block el 4.1


Hi Folks,


i am trying to use tyhe exception handling block of Enterprise library 4.1.


I just createda polisy and used IndexOutOfRangeException and added a replace handler and a logging handler to it.

I am using the NotifyRethrow PostHandlingAction to the exception.


During runtime I am getting an exception on the HandleException event, The exception is added below:



Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 42:             catch (Exception ex)
Line 43:             {
Line 44:                 bool reThrow = ExceptionPolicy.HandleException(ex, "ReplacePolicy");
Line 45:         



Ive 'inherited' some code that creates a HttpWebRequest object to consume a webservice and am working through it to figure out what each bit does.  Ive never consumed webservices this way before (I always create a webreference) so this way of working is new to me.  I can follow all of it except for one bit.  Heres the code Im having trouble understanding

ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytesToWrite = encoding.GetBytes("The message here");

// create web request
const string Action = "http://Awebaddress.org/AProcess"; 
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("The web service url here");

const string contentType = "text/xml; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = contentType;
httpWebRequest.Timeout = -1;
httpWebRequest.ContentLength = bytesToWrite.Length;

the line im having trouble with is this one

Session handling


I am beginner to asp.net. I wanna set up a login page in ASP.NET. I dont like to use ASP.NET's own Login facilities.. I wanna use session object..How will I block visiting "user page" by clicking the back button of the browser after successfull logout 


Pls help me..

Handling external C++ exceptions


Hi. I'm working in a application that uses an external .Dll developed in C++ language. According the business rule, the .Dll can throws one exception if it found a error. My question is if it's possible handle or catch a exception throwed by the C++ dll? The try/catch doesn't works. Bellow there's the code I'm using to call the C++ dll.

        public extern static IntPtr LoadLibrary(string lpLibFileName);

        [DllImport("kernel32", CharSet = CharSet.Ansi)]
        public extern static IntPtr GetProcAddress(IntPtr hLibModule, string procName);

        public extern static bool FreeLibrary(IntPtr hLibModule);

        private delegate void DllMethodCallBack(string param1, string param2);

        public void CallDllMethod(string param1, string param2)

CLR Inside Out: Handling Corrupted State Exceptions


There's a danger in using one-size-fits-all exception handling, and you need to know how to avoid it by being as specific as possible about how you handle errors.

Andrew Pardoe

MSDN Magazine February 2009

Foundations: Error Handling In Workflows


Workflows often define long-running processes and an unhandled failure usually means termination. Avoid this scenario by handling exceptions properly.

Matt Milner

MSDN Magazine February 2009

Patterns in Practice: The Open Closed Principle


Extending an existing codebase can be as productive and frustration-free as writing all new code when you employ the Open Closed Principle. We'll show you how.

Jeremy Miller

MSDN Magazine June 2008

.NET Matters: Handling Messages in Console Apps


Many developers who use the Microsoft .NET Framework think that application type is tied to the libraries that can be used in that application. Stephen Toub clarifies.

Stephen Toub

MSDN Magazine June 2007

Data Points: SQL Server 2005 XML Support, Exception Handling, and More


SQL Server 2005 includes several important improvements to the Transact-SQL (T-SQL) language. One added feature is a new kind of trigger that fires when data definition language (DDL) statements run.

John Papa

MSDN Magazine May 2006

Basic Instincts: Introducing ASP.NET Web Part Connections


When you begin to work with the Microsoft® . NET Framework 2. 0 and ASP. NET, you discover that the new Web Parts infrastructure adds some very powerful functionality to the underlying platform. In the September 2005 issue of MSDN®Magazine, Fritz Onion and I have an article on programming Web Parts titled "ASP.

Ted Pattison

MSDN Magazine February 2006

Data Points: Handling Data Concurrency Using ADO.NET, Part 2


Enterprise development has been moving towards a discon-nected model in recent years and ADO. NET development is no exception. While the disconnected model of the ADO. NET DataSet offers great flexibility, that adaptability also means looser control over data updates than you get with a connected data access model.

John Papa

MSDN Magazine October 2004

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend