1

环境:.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:` 
4

1 回答 1

1

IsSuccessStatusCode 只会在发出 HTTP 请求时返回一个值。如果它无法连接到服务器,则会抛出异常。它适用于 fiddler 运行,因为您的客户端实际上正在连接到 fiddler,然后 fiddler 正在尝试连接到您的服务器。

你有两个选择。要么捕获异常,要么安装在同一端口上运行但使用弱通配符的第二个自托管 Web api。只有在您的主要服务未运行时,第二个服务才会受到影响。

于 2013-08-20T18:08:09.070 回答