Skip to main content
 首页 » 编程设计

c#之WCF 服务之无法调用服务

2024年02月06日12Free-Thinker

我的 WCF 服务有问题,方法本身会收集正确的数据并返回正确的数据类型,但是无论我对端点使用哪种绑定(bind)类型,我总是会遇到相同的错误。我试过 TCP、HTTP 和 NamedPipe。顶部的一般错误如下:

Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.

发布的是来自 HTTP 绑定(bind)。

 An error occurred while receiving the HTTP response to http://localhost:8732/ClubService/. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. 
 
Server stack trace:  
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason) 
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) 
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) 
   at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode) 
   at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode) 
   at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout) 
   at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.Request(Message message, TimeSpan timeout) 
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) 
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) 
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) 
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) 
 
Exception rethrown at [0]:  
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) 
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) 
   at IAndereBoekenService.BoekBeschikbaar(String isbn) 
   at AndereBoekenServiceClient.BoekBeschikbaar(String isbn) 
 
Inner Exception: 
The underlying connection was closed: An unexpected error occurred on a receive. 
   at System.Net.HttpWebRequest.GetResponse() 
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) 
 
Inner Exception: 
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. 
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) 
   at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) 
   at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead) 
 
Inner Exception: 
An existing connection was forcibly closed by the remote host 
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) 
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) 

App.config

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
 
  <system.serviceModel> 
    <services> 
      <service name="ClubServiceLibrary.ClubService"> 
        <host> 
          <baseAddresses> 
            <add baseAddress="net.pipe://localhost/ClubService" /> 
            <add baseAddress ="net.tcp://localhost/ClubService" /> 
            <add baseAddress="http://localhost:8732/ClubService/" /> 
          </baseAddresses> 
        </host> 
        <endpoint name ="namedPipeClub" 
                  binding="netNamedPipeBinding" 
                  contract="ClubServiceLibrary.IClubServiceLibrary" /> 
        <endpoint name="namedPipeClubMEX" 
                  address="mex" 
                  binding="mexNamedPipeBinding" 
                  contract="IMetadataExchange" /> 
        <endpoint name ="tcpClub" 
                  binding="netTcpBinding" 
                  contract="ClubServiceLibrary.IClubServiceLibrary" /> 
        <endpoint name="tcpClubMEX" 
                  address="mex" 
                  binding="mexTcpBinding" 
                  contract="IMetadataExchange" /> 
        <endpoint binding="wsHttpBinding" 
                  name="httpClub" 
                  contract="ClubServiceLibrary.IClubServiceLibrary" /> 
        <endpoint address="mex" 
                  binding="mexHttpBinding" 
                  name="httpClubMEX" 
                  contract="IMetadataExchange" /> 
      </service> 
    </services> 
    <behaviors> 
      <serviceBehaviors> 
        <behavior> 
          <serviceMetadata /> 
        </behavior> 
      </serviceBehaviors> 
    </behaviors> 
  </system.serviceModel> 
</configuration> 

我正在从一个字典中获取我的数据,该字典在另一个名为“DummyData”的类中填充了虚拟数据,它确实填充了数据。

 private static Dictionary<int, Club> clubsValue; 
 
 public static Dictionary<int, Club> Clubs 
        { 
            get { return clubsValue; } 
        } 

在我的ClubService 类 中,我执行以下操作:

  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 
    public class ClubService : IClubService 
    { 
        public List<Club> GetClubByName(string search) 
        { 
            var searchToLower = search.ToLower(); 
 
            List<Club> test = DummyData.Clubs.Values.Where(b => b.Titel.ToLower().Contains(searchToLower)).ToList(); 
 
            return test; 
        } 
    } 

我的 IClubInterface 看起来像这样:

[ServiceContract(Namespace = "http://club.com/clubservice")] 
interface IClubService 
{ 
    [OperationContract] 
    List<Club> GetClubByName(string search); 
} 

所以当调试所有数据都在列表中并且我返回正确的列表时..但是每次我收到此错误消息并且我不知道如何解决这个问题。

请您参考如下方法:

如果我不得不冒险猜测,我会说这类似于在返回时序列化或反序列化数据时抛出的异常。跟踪此错误和大多数其他 WCF 错误的最简单方法是启用 WCF 日志文件并使用 WCF 日志文件查看器查看它生成的内容:

将以下部分添加到您的应用程序配置文件中,然后确保它正在写入跟踪的文件夹存在(在下面的示例中为 c:\temp\WCFLogs)。 您应该开始看到创建了一个 ServerWCFTraces.svclog 文件 - 它可能会说长度为 0 字节,直到您停止服务或它决定刷新到磁盘。

重现失败案例后,在装有 Visual Studio 的机器上打开日志文件(或从此处下载查看器:SvcTraceViewer from MSDN。)

在该 MSDN 链接上有一些使用该工具的说明,但实际上您在事件 Pane (左)中查找错误(以红色突出显示),然后将失败的操作(右上 Pane )归零,然后在在详细信息部分(右下 Pane ),将描述正在抛出的内部异常,它几乎总是告诉您抛出的异常是什么,并为您提供有关如何解决它的更多信息。

<system.diagnostics> 
  <sources> 
     <source propagateActivity="true" name="System.ServiceModel" switchValue="Information, ActivityTracing"> 
        <listeners> 
           <add name="ServiceModelMessageLoggingListener"> 
              <filter type="" /> 
           </add> 
        </listeners> 
     </source> 
     <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing"> 
        <listeners> 
           <add name="ServiceModelMessageLoggingListener"> 
              <filter type="" /> 
           </add> 
        </listeners> 
     </source> 
  </sources> 
  <sharedListeners> 
     <add initializeData="C:\temp\WCFLogs\ServerWCFTraces.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp"> 
        <filter type="" /> 
     </add> 
  </sharedListeners> 
</system.diagnostics>