Handle Unhandled Exception: System.Net.WebException: The request timed out? - c#

I am using web references in my app but I am getting following exception.
I have used bellow code.
obj is my web reference object. It does not take obj directly that is why I have used variable for that. But still it's not working, it takes me automatically to previous activity.
var url=obj.ToString();
// Create a new WebRequest Object to the mentioned URL.
WebRequest myWebRequest=WebRequest.Create(url);
Console.WriteLine("\nThe Timeout time of the request before setting is : {0} milliseconds",myWebRequest.Timeout);
// Set the 'Timeout' property in Milliseconds.
myWebRequest.Timeout=10000;
// This request will throw a WebException if it reaches the timeout limit before it is able to fetch the resource.
WebResponse myWebResponse=myWebRequest.GetResponse();
Unhandled Exception: System.Net.WebException: The request timed out
at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult)
[0x00000] in :0 at
System.Net.HttpWebRequest.GetResponse () [0x00000] in :0 at
System.Web.Services.Protocols.WebClientProtocol.GetWebResponse
(System.Net.WebRequest request) [0x00000] in :0

It hit your timeout, meaning it did not get a response from the URL it called in time.
Check the URL in a browser. Check if it returns anything and how long it takes.
Make sure you don't need to configure a proxy.

Related

WebClient DownloadString not working in ThreadPool

I'm currently have a project where I try to get information from the NZBIndex.nl API using a C# console-application.
My request looks like this:
using (WebClient c = new WebClient())
{
var response = c.DownloadString("https://nzbindex.com/search/json?sort=agedesc&hidespam=1&q=Ubuntu");
Console.WriteLine(response);
//...
}
This worked fine in my main function and when executing it in a manually created thread. But it throws errors when running the code snipped in a function that gets called by a ThreadPool like this:
ThreadPool.QueueUserWorkItem(CheckMethod, item);
The errors that get thrown when running it with ThreadPool look like this:
Thread was being aborted.
at (wrapper managed-to-native) System.Object.__icall_wrapper_mono_threads_state_poll()
at System.Uri.GetComponentsHelper (System.UriComponents uriComponents, System.UriFormat uriFormat) <0x40a23510 + 0x00033> in <4e15bbae9d7043d8afd6cfd50bd9bd5a>:0
at System.Uri.GetComponents (System.UriComponents components, System.UriFormat format) [0x00072] in <4e15bbae9d7043d8afd6cfd50bd9bd5a>:0
at System.Uri.GetParts (System.UriComponents uriParts, System.UriFormat formatAs) [0x00000] in <4e15bbae9d7043d8afd6cfd50bd9bd5a>:0
at System.Uri.get_Query () [0x00041] in <4e15bbae9d7043d8afd6cfd50bd9bd5a>:0
at System.Net.WebClient.GetUri (System.Uri address) [0x00035] in <4e15bbae9d7043d8afd6cfd50bd9bd5a>:0
at System.Net.WebClient.GetUri (System.String address) [0x0004c] in <4e15bbae9d7043d8afd6cfd50bd9bd5a>:0
at System.Net.WebClient.DownloadString (System.String address) [0x00000] in <4e15bbae9d7043d8afd6cfd50bd9bd5a>:0
at (wrapper remoting-invoke-with-check) System.Net.WebClient.DownloadString(string)
at DBErrorcheck.Program.CheckThread (System.Object o) [0x00039] in <cf4c719a35df4ff094732dd5a9e883e9>:0
Debugging it doesn't really help since the programm stops after executing the DownloadString
I just found the answer for this issue while trying to make a minimal reproducable example.
This error seems to be caused when a thread in the ThreadPool is still running but the main already exits. I found this out because with a Thread.Sleep(500) it fixed for me.
I guess a better way would be to check if the Pools has any jobs left.

HttpClient seems to be ignoring the Timeout property

I am trying to load a large amount of data from a server by returning MultiPartContent in the response. However, during the HttpGet method the timeout value I am setting is being ignored. I am trying to set a longer timeout as waiting in this situation is OK.
I have tried various Timeout values between 10 minutes to 2 hours. Realistically the user will only have to wait ~5 minutes the first time they use our app and all other times it will be less.
I have also tried storing a reference of HttpClient to ensure that api.HttpClient isn't re-creating the HttpClient object each time.
var handler = new HttpClientHandler();
var progress = new ProgressMessageHandler(handler);
var api = APIHelpers.GetSession(progress);
progress.HttpReceiveProgress += (e, args) => ProgressChanged.Invoke(e, new SyncEventArgs(GlobalEnums.SyncStage.Downloading, args.ProgressPercentage * 0.01f));
api.HttpClient.Timeout = new TimeSpan(0, 10, 0);
var downloadUri = BuildURI();
var response = await api.HttpClient.GetAsync(downloadUri, HttpCompletionOption.ResponseHeadersRead);
I would expect the application to wait for 10 minutes before throwing a Timeout exception, however the exception is being thrown after 100 seconds (i believe that is the default value?).
Checking the HttpClient.Timeout value after it is set does show that it was set correctly.
The APIHelpers.GetSession() method returns an object of our API with authorisation headers created. The HttpClient object is accessible via an inherited class. This is created by Swashbuckle and Swagger. I have used the api.HttpClient.Timeout = x this way before with success so I don't think this is the issue. It seems to be specific to this scenario in particular.
The exception thrown:
{System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: The operation has timed out.
at System.Net.HttpWebRequest.RunWithTimeoutWorker[T] (System.Threading.Tasks.Task`1[TResult] workerTask, System.Int32 timeout, System.Action abort, System.Func`1[TResult] aborted, System.Threading.CancellationTokenSource cts) [0x000f8] in <a1ab7fc4639d4d84af41d68234158b1c>:0
at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00019] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.14.0.114/src/Xamarin.iOS/mcs/class/System/System.Net/HttpWebRequest.cs:1200
at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <939d99b14d934342858948926287beba>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Http.MonoWebRequestHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x003d1] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.14.0.114/src/Xamarin.iOS/mcs/class/System.Net.Http/MonoWebRequestHandler.cs:499
--- End of inner exception stack trace ---
at System.Net.Http.MonoWebRequestHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x0046a] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.14.0.114/src/Xamarin.iOS/mcs/class/System.Net.Http/MonoWebRequestHandler.cs:503
at Microsoft.Rest.RetryDelegatingHandler+<>c__DisplayClass11_0.<SendAsync>b__1 () [0x000ad] in <6a6c837cafbb4f1faffaba1ff30ca4e3>:0
at Microsoft.Rest.RetryDelegatingHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00150] in <6a6c837cafbb4f1faffaba1ff30ca4e3>:0
at System.Net.Http.Handlers.ProgressMessageHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00087] in <19af20e76ce04547b3fc150a0f8f2d47>:0
at System.Net.Http.HttpClient.SendAsyncWorker (System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) [0x0009e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.14.0.114/src/Xamarin.iOS/mcs/class/System.Net.Http/System.Net.Http/HttpClient.cs:281
at ...
EDIT:
I'm just adding some additional things I have tried in an attempt to solve this.
I have tried using the DependencyService in Xamarin.Forms to get native HttpClientHandlers and HttpClient objects for each platform where I can set the timeouts per platform instead of relying on Xamarin.Forms to translate it for me. This had the exact same result.
public HttpMessageHandler GetHttpHandler(double timeoutSeconds)
{
var sessionConfig = NSUrlSessionConfiguration.DefaultSessionConfiguration;
sessionConfig.TimeoutIntervalForRequest = timeoutSeconds;
sessionConfig.TimeoutIntervalForResource = timeoutSeconds;
sessionConfig.WaitsForConnectivity = true;
var sessionHandler = new NSUrlSessionHandler(sessionConfig);
return sessionHandler;
}
I have tried creating a new HttpClient object just for this API call but with no luck here either. (This replaces Apihelpers.GetSession() in my code)
There was a known issue in both Xamarin.iOS and Xamarin.Android that HttpClient.Timeout values greater than 100 seconds are ignored. This is because the underlying native http clients have a timeout set to 100 seconds, so this times out before the .NET HttpClient times out when the HttpClient.Timeout value > 100 seconds. This should be fixed in all of the latest stable versions, so make sure you are updated. If you are using Visual Studio 2017, you won't have the fix, you will need to get VS 2019 for the fixes.
Had the same issue in my Xamarin Android project. Resolved it by changing HttpClient implementation to Android in the Project properties as below:

HttpClient File Download Error - Unable to read data from the transport connection

I've written an application that in part can download files from a specific web service. The code utilizes an HttpClient to make the calls. The problem is that occasionally I will get a failed request with the following exception message:
Unable to read data from the transport connection: The connection was closed.
I did run across these blog posts, in which the author had to revert the protocol version to 1.0, disable keep alive, and limit the number of service point connections:
http://briancaos.wordpress.com/2012/07/06/unable-to-read-data-from-the-transport-connection-the-connection-was-closed/
http://briancaos.wordpress.com/2012/06/15/an-existing-connection-was-forcibly-closed-by-the-remote-host/
I followed those instructions, as best I knew how and still got the error. I also made sure to keep a single instance of the HttpClient around (following the Singleton principle).
What is interesting is that when running Fiddler I've yet to get the error, which makes me think that there is something that can be done on the client side since Fiddler appears to be doing something to keep the connection alive (though the issue is so sporadic this may be a red herring).
A couple more notes:
The error invariably occurs in the middle of a download (never when initiating the request).
The file continues to download up to the point of failure (there are no extended pauses or delays first).
--UPDATE--
The error occurs on the following line:
responseTask.Wait(cancellationTokenSource.Token);
The following is the full exception:
System.AggregateException occurred HResult=-2146233088 Message=One
or more errors occurred. Source=mscorlib StackTrace:
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at Form1.StartDownload() in c:\Projects\Visual Studio 2012\Demo\Demo\Form1.cs:line 88 InnerException:
System.Net.Http.HttpRequestException
HResult=-2146233088
Message=Error while copying content to a stream.
InnerException: System.IO.IOException
HResult=-2146232800
Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Source=System
StackTrace:
at System.Net.ConnectStream.EndRead(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.WebExceptionWrapperStream.EndRead(IAsyncResult
asyncResult)
at System.Net.Http.Handlers.ProgressStream.EndRead(IAsyncResult
asyncResult)
at System.Net.Http.StreamToStreamCopy.BufferReadCallback(IAsyncResult ar)
InnerException: System.Net.Sockets.SocketException
HResult=-2147467259
Message=An existing connection was forcibly closed by the remote host
Source=System
ErrorCode=10054
NativeErrorCode=10054
StackTrace:
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
InnerException:
--UPDATE #2--
I thought I would try changing the completion option from 'content read' to 'headers read'. This also failed with the same exception, albeit in a different location (where the TODO comment is, reading the content stream).
--UPDATE #3--
I can confirm that the web service (which is hosted in IIS) is aborting the connections (the IIS logs show a win32 status code of 1236 - ERROR_CONNECTION_ABORTED). To try and narrow things down, the MinFileBytesPerSec metabase property was set to zero (on the off chance the client stopped pulling down data momentarily) and the connection is still being aborted. I've double checked all the timeouts and buffer sizes I can think of to no avail. Clawing at thin air at the moment. Any ideas would be appreciated.
Client Setup:
private void SetupClient()
{
// In case we're taxing the web server, limit the number
// connections we're allowed to make to one.
ServicePointManager.DefaultConnectionLimit = 1;
// Set up the progress handler so that we can keep track of the download progress.
_progressHandler = new ProgressMessageHandler();
_progressHandler.HttpReceiveProgress += ProgressHandler_HttpReceiveProgress;
// Create our HttpClient.
_client = HttpClientFactory.Create(_progressHandler);
_client.BaseAddress = new Uri("http://localhost");
_client.Timeout = TimeSpan.FromMinutes(30);
_client.DefaultRequestHeaders.TransferEncodingChunked = true;
}
Download Logic:
private void StartDownload()
{
// Create the request.
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Download"))
{
// Revert the protocol version and turn off keep alive in accordance with:
// http://briancaos.wordpress.com/2012/07/06/unable-to-read-data-from-the-transport-connection-the-connection-was-closed/
// http://briancaos.wordpress.com/2012/06/15/an-existing-connection-was-forcibly-closed-by-the-remote-host/
request.Version = new Version("1.0");
request.Headers.Add("Keep-Alive", "false");
// Set the cancellation token's timeout to 30 minutes.
int timeoutInMilliseconds = 30 * 60 * 1000;
using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(timeoutInMilliseconds))
{
// Making sure that the message isn't "complete" until everything is read in so we can cancel it at anytime.
Task<HttpResponseMessage> responseTask = _client.SendAsync(request, HttpCompletionOption.ResponseContentRead);
responseTask.Wait(cancellationTokenSource.Token);
using (HttpResponseMessage response = responseTask.Result)
{
if (!response.IsSuccessStatusCode)
{
throw new Exception("Request failed!");
}
Task<Stream> streamTask = response.Content.ReadAsStreamAsync();
using (Stream contentStream = streamTask.Result)
{
// TODO: Save to disk.
}
}
}
}
}

Windows phone 8 CommunicationException The remote server returned an error: NotFound

I want to ask a question that make me crazy all this time #_#
I've made an app for windows phone 8 which retrieve data from wcf service.
Luckily, my office mate make me a service for it. But, when I use that service, I got this error.
System.ServiceModel.CommunicationException was unhandled by user code
HResult=-2146233087
Message=The remote server returned an error: NotFound.
Source=System.ServiceModel
StackTrace:
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
at NavFinance.NavFinData.NavcoreNavfinServiceClient.NavcoreNavfinServiceClientChannel.EndGetAll(IAsyncResult result)
at NavFinance.NavFinData.NavcoreNavfinServiceClient.NavFinance.NavFinData.INavcoreNavfinService.EndGetAll(IAsyncResult result)
at NavFinance.NavFinData.NavcoreNavfinServiceClient.OnEndGetAll(IAsyncResult result)
at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)
InnerException: System.Net.WebException
HResult=-2146233079
Message=The remote server returned an error: NotFound.
Source=System.Windows
StackTrace:
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
InnerException: System.Net.WebException
HResult=-2146233079
Message=The remote server returned an error: NotFound.
Source=System.Windows
StackTrace:
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)
InnerException:
After Searching here and there, I got this good article.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj684580(v=vs.105).aspx
But, I read it and still don't get it. Why?
Because my service is write in C# class, not as a web service. So i can't found the IIS service.
Here is my code to generate my data.
public PurchaseInvoiceMainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(purchaseInvoice_Loaded);
}
private void purchaseInvoice_Loaded(object sender, RoutedEventArgs e)
{
NavcoreNavfinServiceClient client = new NavcoreNavfinServiceClient();
client.GetAllCompleted += new EventHandler<GetAllCompletedEventArgs>(client_getAllPurchaseInvoice);
client.GetAllAsync("509A7214-D3A9-47E7-9BB4-232E670ED650");
}
private void client_getAllPurchaseInvoice(object sender, GetAllCompletedEventArgs e)
{
if (e.Error == null)
{
purchaseDataList.ItemsSource = e.Result;
}
}
And, here is my service which return the result.
public System.Collections.ObjectModel.ObservableCollection<NavFinance.NavFinData.vwPurchaseInvoice> EndGetAll(System.IAsyncResult result) {
object[] _args = new object[0];
System.Collections.ObjectModel.ObservableCollection<NavFinance.NavFinData.vwPurchaseInvoice> _result = ((System.Collections.ObjectModel.ObservableCollection<NavFinance.NavFinData.vwPurchaseInvoice>)(base.EndInvoke("GetAll", _args, result)));
return _result;
}
I got the Exception right on this line.
System.Collections.ObjectModel.ObservableCollection<NavFinance.NavFinData.vwPurchaseInvoice> _result = ((System.Collections.ObjectModel.ObservableCollection<NavFinance.NavFinData.vwPurchaseInvoice>)(base.EndInvoke("GetAll", _args, result)));
I've used many trick that i found, starting from upsizing the maxbytes, etc.
It still does not work.
Some one please help me. I really confuse TT_TT
Here is the service that i use.
http://dev.navcore.com/NavFinWebService/Navcore.Navfin.Service.NavcoreNavfinService.svc
Any answer from all of you will make me think more, please give an answer.
Regards,
Budi Prasetyo
This error indicates that your application was unable to communicate with the service. are you try the service URL in the phone/emulator Internet Explorer to be sure the url is accessible?
woah, amazing..!!
after 3 days suffering about this error, finally found something. :)
All the credit should be given to Josue Yeray
Thanks a lot man, why I am not realize about that erlier.
Finally i got my data from my service only by connecting the emulator to the internet.
In my case, usually i used wired connection, and that's not working at all at the emulator.
after searching, i change my connection to wireless connection.
and then, its working and done.
Thanks a lot. :)
Do nothing Extra, Just go and turn off the Firwall of Public and Private both, then wait for 2-3 mins and then run the App. It will run perfect.
I did and it worked.

Properly Handle "Connection reset by peer" in C#

I'm building the c# example here https://github.com/coolaj86/fizzbuzz/blob/master/tcp-echo-csharp/Main.cs and running it against netcat.
When I exit netcat with CTRL + C it closes the socket and I get
Unhandled Exception: System.Net.Sockets.SocketException: Connection reset by peer
at System.Net.Sockets.Socket.EndReceive (IAsyncResult result) [0x00000] in <filename unknown>:0
at echo.AsynchronousSocketListener.ReadCallback (IAsyncResult ar) [0x00000] in <filename unknown>:0
In other languages I've used, the FIN is represented as a read of 0 bytes (or an event called 'FIN' or 'end', etc), but I've modified the example to print out a message for a read of 0 bytes and I see no message.
How to I handle the client closing the connection?
I'm looking for an answer such as "Use System.Net.Foo.Bar.CloseHandler() or System.Net.Foo.Bar.ErrorHandler()".
I'm not sure, but I think there is no way to do it gracefully. Because if connection close properly, you get notification about client disconnection. But interrupting program execution by CTRL + C isn't this case. So I advise you just handle exception to workout this problem.

Categories

Resources