我正在将现有的控制台应用程序迁移到Web应用程序。我正在控制器中进行api调用。下面的代码在控制台应用程序中完美运行。但是在Web应用程序中,我在
var result = webClient.DownloadString(sourceUrl);
消息"unable to connect to remote server"
和内部异常显示{"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}
我尝试将url作为uri对象传递,将web.config文件编辑为包括默认凭据,servicepointmanager等。我还尝试使用async和await使它异步。我真的不知道发生了什么。我在公司代理后面,但是api调用在控制台应用程序和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;
}
}
}
}
答案 0 :(得分:1)
仅需提及的是,在我的家庭网络中尝试了上面的代码并使其工作之后,我将问题确定为代理问题。从我的代码中删除以下内容
IWebProxy wp = WebRequest.DefaultWebProxy;
wp.Credentials = CredentialCache.DefaultCredentials;
webClient.Proxy = wp;
并明确将以下内容添加到web.config中进行了修复。我不知道为什么Web应用程序不从代码中获取默认代理,而控制台应用程序却如此。对于此行为的任何解释将不胜感激。
<system.net>
<defaultProxy>
<proxy usesystemdefault="False" proxyaddress="http://proxy.MYCOMPANY.com:8080" bypassonlocal="True" />
</defaultProxy>
</system.net>