【发布时间】:2019-06-19 18:42:17
【问题描述】:
我正在将现有的控制台应用程序迁移到 Web 应用程序。我正在控制器中进行 api 调用。以下代码在控制台应用程序中完美运行。但是在网络应用程序中,我在
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;
}
}
}
}
【问题讨论】:
-
我会排查客户端到 API 的连接层问题。
-
你好 cmoe。您是否尝试过谷歌搜索错误消息?我发现了这个 SO 帖子:stackoverflow.com/questions/17693353/…
-
嗨,克里斯,我看到了那个链接。这就是我最后一段强调的内容。
-
the api call works perfectly in console app and Postman.Fiddler 是查看不同调用之间差异的好工具。