【问题标题】:Sending byte array to WCF Service将字节数组发送到 WCF 服务
【发布时间】:2015-02-12 16:24:40
【问题描述】:

您好,我尝试了 stackoverflow.com 的所有解决方案,但对我不起作用。

这是我的代码

WCF 服务

public void SendImage(byte[] img, string filename)
{
    MemoryStream memoryStream = new MemoryStream(img);
    FileStream stream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + filename, FileMode.Create);
    memoryStream.CopyTo(stream);
    stream.Close();
}

接口:

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "sendImage")]
void SendImage(byte[] img, string filename);

这是我的 Web.Config

<?xml version="1.0"?>
<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.ServiceModel"
                switchValue="Information, ActivityTracing"
                propagateActivity="true" >
                <listeners>
                    <add name="xml"/>
                </listeners>
            </source>
            <source name="System.ServiceModel.MessageLogging">
                <listeners>
                    <add name="xml"/>
                </listeners>
            </source>
            <source name="myUserTraceSource"
                switchValue="Information, ActivityTracing">
                <listeners>
                    <add name="xml"/>
                </listeners>
            </source>
        </sources>
        <sharedListeners>
            <add name="xml"
                type="System.Diagnostics.XmlWriterTraceListener"
                initializeData="Traces.svclog" />
        </sharedListeners>
    </system.diagnostics>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.serviceModel>
        <diagnostics wmiProviderEnabled="true">
            <messageLogging
                logEntireMessage="true"
                logMalformedMessages="true"
                logMessagesAtServiceLevel="true"
                logMessagesAtTransportLevel="true"
                maxMessagesToLog="3000"
                />
        </diagnostics>
            <services>
                <service name="WcfService1.RestServiceImpl" behaviorConfiguration="ServiceBehaviour">
                    <endpoint address="" binding="basicHttpBinding" contract="WcfService1.IRestServiceImpl" behaviorConfiguration="web">

                    </endpoint>
                </service>
            </services>
            <bindings>
                <!-- 
                    Following is the expanded configuration section for a BasicHttpBinding.
                    Each property is configured with the default value.
                    See the TransportSecurity, and MessageSecurity samples in the
                    Basic directory to learn how to configure these features.
                -->
                <basicHttpBinding>
                    <binding name="Binding1" hostNameComparisonMode="StrongWildcard"
                        receiveTimeout="00:10:00"
                        sendTimeout="00:10:00"
                        openTimeout="00:10:00"
                        closeTimeout="00:10:00"
                        maxReceivedMessageSize="2147483647"
                        maxBufferSize="2147483647"
                        transferMode="Streamed"
                        messageEncoding="Text"
                        bypassProxyOnLocal="false"
                        useDefaultWebProxy="true"
                        maxBufferPoolSize="2147483647">
                    <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <behaviors>
            <serviceBehaviors>
                <behavior name="ServiceBehaviour">
                    <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
                    <!-- 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>
            <endpointBehaviors>
                <behavior name="web">
                    <dataContractSerializer maxItemsInObjectGraph="2147483647"/>    
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>
    <system.web>
        <httpRuntime maxRequestLength="2097151" />
    </system.web>
</configuration>

还有我的 app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <client>
            <endpoint address="http://localhost:55008/RestServiceImpl.svc"
                binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IRestServiceImpl"
                contract="ServiceReference1.IRestServiceImpl"      name="BasicHttpBinding_IRestServiceImpl"/>
        </client>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IRestServiceImpl"
                    hostNameComparisonMode="StrongWildcard"
                    receiveTimeout="00:10:00"
                    sendTimeout="00:10:00"
                    openTimeout="00:10:00"
                    closeTimeout="00:10:00"
                    maxReceivedMessageSize="2147483647"
                    maxBufferSize="2147483647"
                    transferMode="StreamedResponse"
                    messageEncoding="Text"
                    bypassProxyOnLocal="false"
                    useDefaultWebProxy="true"
                    maxBufferPoolSize="2147483647">
                    <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
    </system.serviceModel>
    <system.web>
        <httpRuntime maxRequestLength="2097151" />
    </system.web>
</configuration>

我的问题是为什么我得到:

System.ServiceModel.ProtocolException:远程服务器返回意外响应:(413) 请求实体太大。 ---> System.Net.WebException:远程服务器返回错误:(413)请求实体太大。 在 System.Net.HttpWebRequest.GetResponse() 在 System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan 超时) --- 内部异常堆栈跟踪结束 ---

服务器堆栈跟踪: 在 System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest 请求,HttpWebResponse 响应,HttpChannelFactory 1 工厂,WebException responseException,ChannelBinding 通道绑定) 在 System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan 超时) 在 System.ServiceModel.Channels.RequestChannel.Request(消息消息,TimeSpan 超时) 在 System.ServiceModel.Dispatcher.RequestChannelBinder.Request(消息消息,TimeSpan 超时) 在 System.ServiceModel.Channels.ServiceChannel.Call(字符串操作,布尔单向,ProxyOperationRuntime 操作,Object[] 输入,Object[] 输出,TimeSpan 超时) 在 System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime 操作) 在 System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage 消息)

在 [0] 处重新抛出异常: 在 System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg,IMessage retMsg) 在 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData,Int32 类型) 在 WpfApplication1.ServiceReference1.IRestServiceImpl.SendImage(字节 [] img,字符串文件名) 在 C:\Users\lukgol\documents\visual studio 2010\Projects\WcfService1\WpfApplication1\Service References\ServiceReference1\Reference.cs:line 120 中的 WpfApplication1.ServiceReference1.RestServiceImplClient.SendImage(Byte[] img, String filename) 在 WpfApplication1.MainWindow.buttonSendToServer_Click(Object sender, RoutedEventArgs e) 在 C:\Users\lukgol\documents\visual studio 2010\Projects\WcfService1\WpfApplication1\MainWindow.xaml.cs:line 97

当我运行这段代码时:

private void buttonSendToServer_Click(object sender, RoutedEventArgs e)
{
    imageCtrl.Source = null;
    ServiceReference1.RestServiceImplClient service = new ServiceReference1.RestServiceImplClient();
    foreach (MyBitmap bit in listBitmap)
    {
        string s;
        try
        {
            service.SendImage(bit.GetBytes(), bit.FileName);
        }
        catch (ProtocolException ex)
        {
            s = ex.ToString();
        }
    }
    service.Close();
}

【问题讨论】:

  • 请包括您尝试上传的文件的大小以及您尝试过的任何 IIS 配置。
  • 我还注意到您的绑定使用“文本”而不​​是“二进制”进行编码,这可能是您想要的。乍一看,绑定中的其他设置看起来足够大,可以容纳您的文件。
  • 您可以选择在 WCF 中实现流式传输。

标签: c# .net wpf wcf


【解决方案1】:

在 WCF 端(即,与 IIS 分开),您没有使用在服务配置文件 (Binding1) 中定义的绑定:

<endpoint address="" binding="basicHttpBinding"
          contract="WcfService1.IRestServiceImpl" 
          behaviorConfiguration="web">

您指定要使用的绑定的类型,但由于您没有指定要使用的配置,您将获得basicHttpBinding 的默认设置。要指定绑定配置,请使用bindingConfiguration 属性,如下所示:

<endpoint address="" binding="basicHttpBinding" 
          bindingConfiguration="Binding1"
          contract="WcfService1.IRestServiceImpl"
          behaviorConfiguration="web">

可能还有其他配置,但从 WCF 的角度来看,这是最常见的原因。

【讨论】:

  • 是的,太好了!我花了几个小时寻找解决方案。非常感谢,现在运行非常好。问候。
猜你喜欢
  • 2014-02-03
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多