System.Net.WebException: The request was aborted: The request was canceled

In one of our programs I had to fetch some data in a loop from a SAP WebService in a .NET 3.5 application. However, for some requests the “The request was aborted: The request was canceled” WebException was thrown.

It took me a while to find the solution and there are few unsolved threads in google’s top results, so I’ll post the solution that worked for me. In my case, it could be solved by setting KeepAlive setting of the HttpWebRequest to false.

Based on the article explaining how to do it in Visual Basic for .NET (and why) and this thread, if you are using WebService, you can do it this way:

  1. In Visual Studio Solution Explorer toggle on Show all files button
  2. Navigate to the WebService reference which causes problems, find and open Reverence.cs file (or Reference.vb for Visual Basic)
  3. Add an overriden method to the file:

or in Visual Basic:

You only need to remember, that the file will be re-generated when you update the web reference, so in that case you will have to apply the trick again.