wpf 将字节数组发送到 WCF 服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28482571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending byte array to WCF Service
提问by ?ukasz Golec
Hello I tried all solutions from stackoverflow.com but it didn't work for me.
您好,我尝试了来自 stackoverflow.com 的所有解决方案,但对我不起作用。
Here is my code
这是我的代码
WCF Service:
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();
}
Interface:
界面:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "sendImage")]
void SendImage(byte[] img, string filename);
Here is my Web.Config:
这是我的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>
And my app.config:
我的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>
My question is why I get:
我的问题是为什么我得到:
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
System.ServiceModel.ProtocolException:远程服务器返回意外响应:(413) 请求实体太大。---> System.Net.WebException:远程服务器返回错误:(413) 请求实体太大。在 System.Net.HttpWebRequest.GetResponse() 在 System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) --- 内部异常堆栈跟踪结束---
服务器堆栈跟踪:在 System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) 的 System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory 1 factory, WebException responseException, ChannelBinding channelBinding) ) 在 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 操作,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 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: 97
When I run this code:
当我运行此代码时:
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();
}
采纳答案by Tim
On the WCF end (i.e., separate from IIS), you're not using the binding you defined in the service config file (Binding1):
在 WCF 端(即与 IIS 分开),您没有使用您在服务配置文件 ( Binding1) 中定义的绑定:
<endpoint address="" binding="basicHttpBinding"
contract="WcfService1.IRestServiceImpl"
behaviorConfiguration="web">
You specify the typeof binding to use, but since you didn't specify the configuration to use, you will get the default settings for basicHttpBinding. To specify the binding configuration, use the bindingConfigurationattribute, like this:
您指定要使用的绑定类型,但由于您没有指定要使用的配置,您将获得basicHttpBinding. 要指定绑定配置,请使用该bindingConfiguration属性,如下所示:
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="Binding1"
contract="WcfService1.IRestServiceImpl"
behaviorConfiguration="web">
There could be other configurations to, but this is the most common reason from a WCFperspective.
可能还有其他配置,但从WCF 的角度来看,这是最常见的原因。

