【问题标题】:Unable to interact with an API in web app but it works in console app无法与 Web 应用程序中的 API 交互,但它可以在控制台应用程序中工作
【发布时间】: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 是查看不同调用之间差异的好工具。

标签: c# asp.net webclient


【解决方案1】:

只是提一下,在我的家庭网络中尝试了上述代码并且它有效之后,我将问题确定为代理问题。从我的代码中删除以下内容

 IWebProxy wp = WebRequest.DefaultWebProxy;
    wp.Credentials = CredentialCache.DefaultCredentials;
    webClient.Proxy = wp;

并将以下内容显式添加到 web.config 修复它。我不知道为什么网络应用程序不会从代码中获取默认代理,但控制台应用程序会。对此行为的任何解释将不胜感激。

<system.net>
    <defaultProxy>
      <proxy usesystemdefault="False" proxyaddress="http://proxy.MYCOMPANY.com:8080" bypassonlocal="True" />
    </defaultProxy>
  </system.net>

【讨论】:

    猜你喜欢
    • 2011-09-05
    • 2013-07-28
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2016-09-28
    • 1970-01-01
    • 2020-07-09
    相关资源
    最近更新 更多