WebClient DownloadData SocketException - c#

This is a very popular topic here, and I have read at least twenty different stackoverflow, expertsexchange, codeproject "solutions", and they boil down to things like: proxy servers (which they assure me isn't being used), and other things that just don't help me.
I have an image that is sitting out on this server. It can be publicly reached through a URL (I won't give that here, being this is a customer server). The URL that is exposed is through a Virtual Directory that is set up through IIS.
I opened Visual Studio and created a new ASP.NET Web Application - and I made it an empty project, and added one WebForm to it. Simple as simple can be.
The only code I added was to the WebForm Page_Load function:
protected void Page_Load(object sender, EventArgs e)
{
using (System.Net.WebClient wc = new System.Net.WebClient())
{
Uri myUri = new Uri(#"http://SERVER/folder/Image.bmp", UriKind.Absolute);
byte[] bytes = wc.DownloadData(myUri);
}
}
That's it. That's all I do.
Because that URL is publicly exposed, when I run it in Visual Studio. It works.
Also, at work, I have a Web Server with IIS (The IIS that comes with Windows Server 2008 R2 Standard - Service Pack 1). I just copied my whole project folder (after I built for release), plopped it on inetpub/wwwroot/, went to IIS, added it as an Application (using annonymous access, and the Default App Pool).
Here, at work, no problem! No errors.
Now, I do the same thing to their server. Just take the whole folder. Create an application, etc. etc. .... and as soon as I get to the DownloadData piece of code I get an 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 [redacted]:80
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.Net.Sockets.SocketException: 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 [redacted]:80
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SocketException (0x274c): 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 [redacted]:80]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +8409635
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +611
[WebException: Unable to connect to the remote server]
System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +365
System.Net.WebClient.DownloadData(Uri address) +111
WebClientTest.WebForm1.Page_Load(Object sender, EventArgs e) in c:\Users\[me!!!]\Documents\Visual Studio 2013\Projects\WebClientTest\WebClientTest\WebForm1.aspx.cs:18
System.Web.UI.Control.OnLoad(EventArgs e) +103
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3811
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2053.0
So, to recap:
Simple project works in my debugging environment. Check!
Works on my server at work. Check!
Doesn't work on client server. Not Check!
There has to be some explanation for this. Obviously I can see the host. So why, when they host this code, instead of me, does it fail to establish a connection? Finding this information, or what can cause this, is surprisingly difficult. It has to be some type of server setting, right?
Their server is Windows Server 2012 R2 Standard.
EDIT: I also want to mention that I can open a browser anywhere (my desktop, my VM which hosts my debugging environment, their server, etc.) and if I take that URL, the bitmap displays. No problem. As soon as IIS/ASP.NET get involved ... connections fail. This is so discouraging.
EDIT2: I have a public facing cloud server, that has the same setup (same type of virtual directory, an image, etc). So I added a second WebForm to this project. Same code in PageLoad, this time pointing to my server for the image, instead of theirs. That page works! There's definitely something on their server that is causing this. But what?

Related

Calling REST service via HttpClient from ASP.net 4 Web API 2 project results in exception

Current Situation: I have created an ASP.net project (web project) using the WebAPI 2 template. One of the HTTPGET method now tries to make a request to another REST API using the following code.
[HttpGet]
public string Get()
{
var uri = #"http://api.../...";
var httpClient = new HttpClient();
var response = httpClient.GetAsync(uri).GetAwaiter().GetResult(); // <- exception here
response.EnsureSuccessStatusCode();
string content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return content;
}
At the line, marked with the comment, the following HttpRequestException with the message "Unable to connect to the remote server" (inner exception) is thrown.
System.Net.Http.HttpRequestException was unhandled by user code
HResult=-2146233088
Message=An error occurred while sending the request.
Source=mscorlib
...
InnerException:
HResult=-2146233079
Message=Unable to connect to the remote server
Source=System
StackTrace:
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
InnerException:
ErrorCode=10060
HResult=-2147467259
Message=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 ...
NativeErrorCode=10060
Source=System
StackTrace:
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
InnerException:
What I tried so far:
I used the exact same URI (via copy & paste) in the browser and the JSON with some data is returned.
Before creating the WebAPI2 project I played around with the RC candidate of ASP.net 5. I created a project based on the ASP.net 5 template "Web API". There I have the exact same code and it is working fine.
Assumption: My assumption is that the config in the ASP.net 4 Web API 2 template has some config that prevents from getting a response. I found some similar question on SO where it seems that some private networking was disabled.
Question: What does prevent the response from being received when using HttpClient in a ASP.net 4 Web API 2 based project?
I was able to find out what the root cause is. The short answer is that the ASP.net 5 template used a proxy, probably one that is configured via Windows group policies, while the ASP.net 4 template directly connected to the other REST service. But because this is prohibited by some firewall it didn't work.
Long answer: In order to check the network traffic of both templates (ASP.net 4 and 5) I used Process Monitor from sysinternals tools. I set a filter to IISExpress.exe and dnx.exe.
For the ASP.net 4 template this looked as follows.
There are only two entries where you can see that IISExpress directly connects to the REST service. In case of ASP.net 5 there are a lot more entries because instead of a direct connection it uses a proxy. I actually assumed that this is a proxy because of its host name. One point to note here is that instead of IISExpress.exe, dnx.exe is building up the connection.
In order to let IISExpress use a proxy for the ASP.net 4 template I added the following lines into the projects web.config. I used the hostname and port as shown in Process Monitor.
<system.net>
<defaultProxy>
<proxy usesystemdefault="True"
proxyaddress="http://proxy.<hostname>:<port>"
bypassonlocal="True"/>
</defaultProxy>
</system.net>
So my assumption is that somewhere in Windows this proxy is configured, probably via group policies(?). Firefox, dnx.exe, and others are using this configuration. But IISExpress ignores this and therefore does not receive an answer from the REST API.
It is happening may be he has not allowed Public to use, there may be some specific domains allowed. As what it seems to me.
You can read this article for better understanding :
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

The underlying connection was closed: An unexpected error occured on a send

I am trying to run/debug locally my cloud project, but service bus connection keeps crashing with error:
<15:46:59> MessagingFactory successfully created
<15:47:39> Exception: The underlying connection was closed: An unexpected error occurred on a send..
....
System.IO.IOException: Unable to read data from the transport connection:
An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)}
Also I receive this error when using Service Bus Explorer tool.
When deploy to cloud everything works ok, service bus connection is ok.
Can anyone help me with this? what could be the reason?
Thank you in advance!
Maybe the problem is with the SSL certificate validation protocol. Try this to force the latest protocol type.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
There are several reason leading to such error so you may check the following
You have configured the settings correctly.
Firewall in your system allows the connection (protocol, host & port)
DNS servers configured in your network are able to resolve the host.
Your ISP is not blocking your connection due to any reason
Since there is no fixed solution for your error, you may have to work a little hard to figure out the actual issue. You may also find some useful information from the log files if enabled.

Avoiding the timeout exception while connecting to a https url to send request to a web-service

In a dotNet mvc application, while trying to send requests to a http url, my application is working as expected. However, when I try to send requests to a https url, I get the following error ( upon publishing the app in IIS and running it in a web browser) :
Server Error in '/dotnetstage' Application.
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 10.63.64.146:443
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.Net.Sockets.SocketException: 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 10.63.64.146:
I understand that it has got something to do with the SSL certificates, so I found that there's a way to ignore certificate validation:
WebRequest webRequest = WebRequest.Create(reqURL);
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; }; //this line works for the certificate validation ignoring
Even then, I am getting the same error. I have two queries:
Am I adding the ServicePointManager line at the proper place? If not
what is the correct location where you add this in your code?
Is there anything else I need to take care of ?
Any help or at least a pointer towards the right approach will be higly appreciated. Stack Overflow helped me a lot with learning to code in c# mvc apps and build complex caller applications in a matter of 4 weeks and I look forward to getting a quick solution to this as well. Thanks. :)
The ServerCertificateValidationCallback should be defined first before making the web request. But in your case the issue is totally different it could be that the web server side code crashed before it could send a response back.

A connection attempt failed because the connected party did not properly respond after a period of time or connected host has failed to respond

I'm developing a windows service, that downloads images from a specific URL. The service runs correctly on my computer but when I install it in the server it does not download the image and it gives the following error:
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: 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 212.100.220.117:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadData(Uri address)
at System.Net.WebClient.DownloadData(String address)
What might be causing the error and how can I resolve it?
I read this page:
http://support.microsoft.com/kb/318140
I'm not sure if this is the problem, and if it is what proxy should I write in the config. Asking you for your advice.
I found the answer. I was trying to access the public address "http://mywebsite.com/images/" from the server. Instead of that I used the local IP of the server hosted the website and it's now working.
In this case it might be possible that port 80 is not open. Create an inbound and outbound rule in firewall setting to open port 80. Still, if the issue exists try with disabling the antivirus, It might be possible that antivirus is blocking the port.
In my case I had to modify the Logon settings of the Windows Service in the Windows Service console then used domain administrator account to run the service instead of the regular Local System/Service account then It started working properly.
If you are working, this could indicate that you aren't connected to your VPN.

Wince Socket exception on asynchronous HTTP request

I am writing a WinCE app in C# that makes an HTTP POST to an APACHE server residing on my network. Because of some network issues (I am guessing), I get the following exception in the managed code
System.Net.Sockets.SocketException occurred
Message="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"
ErrorCode=10060
NativeErrorCode=10060
StackTrace:
at System.Net.Sockets.Socket.ConnectNoCheck(EndPoint remoteEP)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at System.Net.Connection.doConnect(IPEndPoint ep)
at System.Net.Connection.connect(Object ignored)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
This exception isn't always thrown, but when it is thrown, my app fails to connect to the server AT ALL. Repeated connection attempts don't help in reconnecting either. The only thing that helps is closing and re-deploying the app.
I can't catch the exception because its inside of managed code. Is there any way to circumvent this and close all socket connections to my server and re-initialize them? Is there something I am doing wrong?
The exception message looks a bit misleading ("connection attempt failed because the connected party") but I think it means your hardware is communicating with the server, but the server is not accepting the connection on the TCP level.
A problem I could think of is "hanging" connections, causing the server to reach the maximum number of concurrent connections and to stop accepting new ones.
Although it's just a guess, you might want to check the apache log if you can to see if you can find out if the server reports anything, and perhaps try restarting apache as soon as the problem occurs again. If that helps, you still need to find the cause of course.

Categories