将字节数组发送到WCF服务

时间:2015-02-12 16:24:40

标签: c# .net wpf wcf

您好我尝试了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)请求实体太大。 ---&GT; System.Net.WebException:远程服务器返回错误:(413)请求实体太大。     在System.Net.HttpWebRequest.GetResponse()     at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)     ---内部异常堆栈跟踪结束---

     

服务器堆栈跟踪:     在System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest请求,HttpWebResponse响应,HttpChannelFactory 1工厂,WebException responseException,ChannelBinding channelBinding)     at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)     在System.ServiceModel.Channels.RequestChannel.Request(消息消息,TimeSpan超时)     在System.ServiceModel.Dispatcher.RequestChannelBinder.Request(消息消息,TimeSpan超时)     在System.ServiceModel.Channels.ServiceChannel.Call(String action,Boolean oneway,ProxyOperationRuntime operation,Object [] ins,Object [] outs,TimeSpan timeout)     在System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall,ProxyOperationRuntime操作)     在System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

     

在[0]处重新抛出异常:     在System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg,IMessage retMsg)     在System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData,Int32 type)     at WpfApplication1.ServiceReference1.IRestServiceImpl.SendImage(Byte [] img,String filename)     at WpfApplication1.ServiceReference1.RestServiceImplClient.SendImage(Byte [] img,String filename)在C:\ Users \ lukgol \ documents \ visual studio 2010 \ Projects \ WcfService1 \ WpfApplication1 \ Service References \ ServiceReference1 \ Reference.cs:line 120     at WpfApplication1.MainWindow.buttonSendToServer_Click(Object sender,RoutedEventArgs e)位于C:\ Users \ lukgol \ documents \ visual studio 2010 \ Projects \ WcfService1 \ WpfApplication1 \ MainWindow.xaml.cs:第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();
}

1 个答案:

答案 0 :(得分:2)

在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 角度来看最常见的原因。