环境:.net 4.0 控制台应用程序
Microsoft.AspNet.WebApi.Client version=4.0.30506.0 targetFramework="net40"
Microsoft.Net.Http" version=2.0.20710.0 targetFramework="net40"
Newtonsoft.Json version=4.5.11 targetFramework="net40"
好的,所以我已经设置了一个自托管的 Web API 服务,并且我可以毫无问题地访问该服务。我想优雅地处理服务未运行的情况。
问题是 GetAsync 调用中的代码错误,甚至在它可以检查 IsSuccessStatusCode 之前。
但是,如果我启动 Fiddler,那么代码会按预期运行,这对我来说真的很奇怪。
这是一些演示代码。
Private Function GetConnInfo(hostIP As String, hostPort As Integer) As Boolean
GetConnInfo = False
Dim client As HttpClient = New HttpClient()
client.BaseAddress = New Uri("http://" & hostIP & ":" & hostPort)
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
Dim resp = client.GetAsync("api/clientconnectioninfo/GetAllConnections").Result
If resp.IsSuccessStatusCode Then
GetConnInfo = True
End If
Return GetConnInfo
End Function
堆栈跟踪:
System.AggregateException was unhandled
HResult=-2146233088
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at DemoApiServiceNotRunning.Module1.GetConnInfo(String hostIP, Int32 hostPort) in C:\Users\tonye\Documents\Visual Studio 2012\Projects\DemoApiServiceNotRunning\DemoApiServiceNotRunning\Module1.vb:line 19
at DemoApiServiceNotRunning.Module1.Main() in C:\Users\tonye\Documents\Visual Studio 2012\Projects\DemoApiServiceNotRunning\DemoApiServiceNotRunning\Module1.vb:line 8
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.Http.HttpRequestException
HResult=-2146233088
Message=An error occurred while sending the request.
InnerException: System.Net.WebException
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: System.Net.Sockets.SocketException
ErrorCode=10061
HResult=-2147467259
Message=No connection could be made because the target machine actively refused it 192.168.20.124:8700
NativeErrorCode=10061
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:`