2015-02-12 4 views
2

Здравствуйте, я пробовал все решения из stackoverflow.com, но это не сработало для меня.Отправка байтового массива в службу WCF

Вот мой код

службы 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: The remote server returned an unexpected response: (413) Request Entity Too Large. ---> System.Net.WebException: The remote server returned an error: (413) Request Entity Too Large. at System.Net.HttpWebRequest.GetResponse() at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) --- End of inner exception stack trace ---

Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory 1 factory, WebException responseException, ChannelBinding channelBinding) at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) at System.ServiceModel.Channels.RequestChannel.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 WpfApplication1.ServiceReference1.IRestServiceImpl.SendImage(Byte[] img, String filename) at WpfApplication1.ServiceReference1.RestServiceImplClient.SendImage(Byte[] img, String filename) in 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) in 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(); 
} 
+0

Пожалуйста, укажите размер файла, который вы хотите загрузить, и любые настройки IIS, которые вы пробовали. – moarboilerplate

+0

Я также заметил, что ваша привязка использует «текст», а не «двоичную» для кодировки, которая может быть тем, что вы хотите. На первый взгляд другие настройки в вашей привязке выглядят достаточно большими, чтобы разрешить ваш файл. – moarboilerplate

+0

, возможно, вы могли бы реализовать потоковое вещание в WCF. –

ответ

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.

+0

Да, отлично! Я провожу несколько часов, чтобы найти решение. Большое спасибо, теперь бегает фантастически. С уважением. –