【发布时间】:2016-08-07 05:57:41
【问题描述】:
现状:我使用 WebAPI 2 模板创建了一个 ASP.net 项目(网络项目)。现在,其中一个 HTTPGET 方法尝试使用以下代码向另一个 REST API 发出请求。
[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;
}
在标有注释的行中,抛出以下带有“无法连接到远程服务器”消息的HttpRequestException(内部异常)。
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:
到目前为止我尝试了什么:
- 我在浏览器中使用了完全相同的 URI(通过复制和粘贴),并返回了带有一些数据的 JSON。
- 在创建 WebAPI2 项目之前,我使用了 ASP.net 5 的 RC 候选对象。我基于 ASP.net 5 模板“Web API”创建了一个项目。我有完全相同的代码,并且运行良好。
假设: 我的假设是 ASP.net 4 Web API 2 模板中的配置有一些配置阻止了响应。我在 SO 上发现了一些类似的question,似乎某些私有网络已被禁用。
问题:在基于 ASP.net 4 Web API 2 的项目中使用 HttpClient 时,什么会阻止接收响应?
【问题讨论】:
-
你能试试其他的get方法比如
GetStringAsync(String)吗? -
完全一样的结果
标签: c# asp.net asp.net-web-api