Reputation: 191
I'm migrating my existing console app to a web app. I'm making an api call in the controller. The below code works perfectly in console app. But in web app,i get exception at
var result = webClient.DownloadString(sourceUrl);
with the message "unable to connect to remote server"
and the inner exception says {"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}System.Exception {System.Net.Sockets.SocketException}
I have tried to pass the url as uri object, edited web.config file to include default credentials, servicepointmanager etc. I have also tried to make it asynchronous using async and await. I really do not know what is going on. I'm behind a corporate proxy but the api call works perfectly in console app and Postman.
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
namespace webApp.Controllers
{
public class DataController : ApiController
{
private string sourceUrl="http://api.openweathermap.org/data/2.5/weather?zip=94040,us&appid=YOURID";
[Route("")]
public void GetAlldata()
{
var dataCall = DownloadData(sourceUrl);
}
private string DownloadData(string url)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var webClient = new WebClient();
IWebProxy wp = WebRequest.DefaultWebProxy;
wp.Credentials = CredentialCache.DefaultCredentials;
webClient.Proxy = wp;
var result = webClient.DownloadString(sourceUrl);
return result;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}
Upvotes: 0
Views: 1307
Reputation: 97
Íf above solution(cmoe's answer) don't work for your case. May be The console app pass proxy but other app drop by firewall. Check firewall settings.
Upvotes: 0
Reputation: 191
Just to mention that after trying the above code in my home network and it worked, I pinpointed the problem to be a proxy issue. Removing the below from my code
IWebProxy wp = WebRequest.DefaultWebProxy;
wp.Credentials = CredentialCache.DefaultCredentials;
webClient.Proxy = wp;
and explicitly adding the below to web.config fixed it. I don't know why web app doesn't pickup the default proxy from code but console app does. Any explanation for this behavior will be appreciated.
<system.net>
<defaultProxy>
<proxy usesystemdefault="False" proxyaddress="http://proxy.MYCOMPANY.com:8080" bypassonlocal="True" />
</defaultProxy>
</system.net>
Upvotes: 2