c# - WCF从客户端发送int[]到服务器

标签 c# .net wcf visual-studio-2010

我遇到这个问题:

我有一个 WCF 服务,它公开了此操作契约:

[OperationContract]
void Index(int[] song, string fileName);

在我的客户端上,我有:

AudioDetectionServiceReference.AudioDetectionServiceClient client = new AudioDetectionServiceReference.AudioDetectionServiceClient();
client.Index(max.ToArray(), mp3Files[i]);

其中 max 是包含 2000 个 int 值的数组,mp3Files[i] 是包含 200 个字符的字符串。

Web.config 有这个:

<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
  <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

app.config 有:

    <configuration>
        <system.serviceModel>

            <bindings>
                <basicHttpBinding>
                    <binding name="BasicHttpBinding_IAudioDetectionService" closeTimeout="00:01:00"
                        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                        allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                        useDefaultWebProxy="true">
                        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                        <security mode="None">
                            <transport clientCredentialType="None" proxyCredentialType="None"
                                realm="" />
                            <message clientCredentialType="UserName" algorithmSuite="Default" />
                        </security>
                    </binding>
                </basicHttpBinding>
            </bindings>
            <client>
                <endpoint address="http://localhost:15863/AudioDetectionService.svc"
                    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IAudioDetectionService"
                    contract="AudioDetectionServiceReference.IAudioDetectionService"
                    name="BasicHttpBinding_IAudioDetectionService" />
            </client>
        </system.serviceModel>
    <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

现在是棘手的部分:

右键单击服务引用,进入配置服务引用,有一个名为集合类型的选项。如果我将集合类型设置为“Syste.Array”,则会收到错误

The remote server returned an unexpected response: (400) Bad Request.

使用堆栈跟踪:

    Server stack trace: 
       at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding)
       at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
       at System.ServiceModel.Channels.RequestChannel.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 SqlTest.AudioDetectionServiceReference.IAudioDetectionService.Index(Int32[] song, String fileName)
       at SqlTest.AudioDetectionServiceReference.AudioDetectionServiceClient.Index(Int32[] song, String fileName) in blablabla\Service References\AudioDetectionServiceReference\Reference.cs:line 53
       at SqlTest.Program.Main(String[] args) in blablabla\Program.cs:line 46

当我将其更改为“System.Collection.Generic.List”时,错误神奇地消失了。

我的问题是:为什么?

第二个问题:

为什么这有效?

client.Index(max.Take(100).ToArray(), mp3Files[i]);

使用相同的上下文(app.config、web.config 以及与上面相同的代码,并选择 System.Array)。

谢谢, 安德烈·内古

PS:我发布此内容是因为我花了 2 天的时间尝试更改绑定(bind)设置、更改消息大小、更改 readerQuotas 的值和其他内容,而我不得不做这个愚蠢的选择。所以我很生气,我至少想从中学到一些东西。

最佳答案

经过更多挖掘,这就是我所做的更改:

应用程序配置

<bindings>
    <basicHttpBinding>
        <binding name="BasicHttpBinding_IAudioDetectionService" closeTimeout="00:01:00"
            openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
            allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
            maxBufferSize="655360" maxBufferPoolSize="5242880" maxReceivedMessageSize="655360"
            messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
            useDefaultWebProxy="true">
            <readerQuotas maxDepth="320" maxStringContentLength="81920" maxArrayLength="163840"
                maxBytesPerRead="40960" maxNameTableCharCount="163840" />
            <security mode="None">
                <transport clientCredentialType="None" proxyCredentialType="None"
                    realm="" />
                <message clientCredentialType="UserName" algorithmSuite="Default" />
            </security>
        </binding>
    </basicHttpBinding>
</bindings>
<client>
    <endpoint address="http://localhost:15863/AudioDetectionService.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IAudioDetectionService"
        contract="AudioDetectionServiceReference.IAudioDetectionService"
        name="BasicHttpBinding_IAudioDetectionService" />
</client>

对于服务器,请注意 basicHttpBinding 部分没有名称。我认为如果该部分有名称,WCF 生成的默认服务将忽略它。

<bindings>
  <basicHttpBinding>
    <binding closeTimeout="00:01:00"
        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
        allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
        maxBufferSize="655360" maxBufferPoolSize="5242880" maxReceivedMessageSize="655360"
        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
        useDefaultWebProxy="true">
      <readerQuotas maxDepth="320" maxStringContentLength="81920" maxArrayLength="163840"
          maxBytesPerRead="40960" maxNameTableCharCount="163840" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
            realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>

对于其他值,我在末尾添加了 0(乘以 10)。我认为增加它们会让你转移更多的事件。但最重要的是,basicHttpBinding 没有名称。如果它有名字,我认为它被忽略了。

我不会将其设置为已回答,因为问题是为什么 System.Array 抛出异常而 System.Generic.List 不抛出异常。

关于c# - WCF从客户端发送int[]到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10710361/

相关文章:

.net - DateTimeOffsetAdapter干扰DateTimeOffset对象的WCF序列化

c# - OpenXML Power Tools 编译时出现问题 : 'OutputTypeAttribute' could not be found

wcf - 将服务引用添加到 Windows 服务中托管的 WCF 服务时出现问题

c# - 针对自托管 Web API (OWIN/Katana) 验证 MVC 客户端

c# - DirectoryServices.DirectoryEntry 组调用 ("remove") 和属性 ["member"].remove 之间的差异

c# - SQL - group by 两列聚合问题

.net - GAC 和程序集版本控制

wcf - 在 Visual Studio 中构建 WCF 项目时的输出目录

c# - 为 Razor 页面创建别名

c# - ASP.NET,将默认屏幕大小设置为 1024x768