[英]HTTPClient error when calling ASP.NET Web API REST service from ASP.NET MVC app
[英]Calling REST service via HttpClient from ASP.net 4 Web API 2 project results in exception
当前情况:我已经使用WebAPI 2模板创建了一个ASP.net项目(Web项目)。 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:
到目前为止我尝试过的是:
假设:我的假设是ASP.net 4 Web API 2模板中的配置具有阻止获取响应的某些配置。 我在SO上发现了类似的问题 ,似乎某些专用网络已被禁用。
问题:在基于ASP.net 4 Web API 2的项目中使用HttpClient时,如何阻止收到响应?
我能够找出根本原因是什么。 简短的答案是ASP.net 5模板使用了一个代理(可能是通过Windows组策略配置的代理),而ASP.net 4模板直接连接到了其他REST服务。 但是由于某些防火墙禁止这样做,所以它不起作用。
长答案:为了检查两个模板(ASP.net 4和5)的网络流量,我使用了sysinternals工具中的Process Monitor。 我将过滤器设置为IISExpress.exe和dnx.exe。
对于ASP.net 4模板,如下所示。
只有两个条目可以看到IISExpress直接连接到REST服务。 对于ASP.net 5,会有更多条目,因为它使用代理而不是直接连接。 我实际上假设这是一个代理,因为它的主机名。 这里要注意的一点是,dnx.exe代替了IISExpress.exe,正在建立连接。
为了让IISExpress使用ASP.net 4模板的代理,我在项目web.config
添加了以下几行。 我使用了主机名和端口,如进程监视器中所示。
<system.net>
<defaultProxy>
<proxy usesystemdefault="True"
proxyaddress="http://proxy.<hostname>:<port>"
bypassonlocal="True"/>
</defaultProxy>
</system.net>
因此,我的假设是在Windows中某个位置可能通过组策略(?)配置了该代理。 Firefox,dnx.exe等使用此配置。 但是IISExpress忽略了这一点,因此没有收到来自REST API的答复。
可能是由于他不允许公众使用,可能允许了某些特定的域。 就像在我看来。
您可以阅读本文以获得更好的理解: http : //www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.