2015-05-06 128 views
0

當我通過其他項目中的反射從WindowsForm發送大量字符串到WCF時,出現錯誤。我看到我需要在web.config中的服務器和app.config客戶端(winform)中放置一些參數。我做到了,但我有同樣的例外。 另外,當我生成實例時,我在客戶端中放置了任何C#代碼行。 在C#中的代碼通過WCF發送異常(System.Reflection.TargetInvocationException)請求

CompilerParameters compilerParameters = new CompilerParameters(new string[] { "System.dll", "System.ServiceModel.dll", "System.Runtime.Serialization.dll" }); 
      compilerParameters.GenerateInMemory = true; 

      //Gets the compiled assembly. 
      compilerResults = codeDomProvider.CompileAssemblyFromDom(compilerParameters, serviceContractGenerator.TargetCompileUnit); 

    //implemented by all the communication oriented objects). 
       Type proxyType = compilerResults.CompiledAssembly.GetTypes().First(t => t.IsClass && t.GetInterface(contractName) != null); 


       // Now we get the first service endpoint for the particular contract. 
       ServiceEndpoint serviceEndpoint = endpointsForContracts[contractName].First(); 

       // Create an instance of the proxy by passing the endpoint binding and address as parameters. 
       proxyInstance = compilerResults.CompiledAssembly.CreateInstance(proxyType.Name, false, System.Reflection.BindingFlags.CreateInstance, null, 
        new object[] { serviceEndpoint.Binding, serviceEndpoint.Address }, System.Globalization.CultureInfo.CurrentCulture, null); 

       //Set timeOut in minutes 
       PropertyInfo channelFactoryProperty = proxyInstance.GetType().GetProperty("ChannelFactory"); 

       if (channelFactoryProperty == null) 
       { 
        throw new InvalidOperationException("There is no ''ChannelFactory'' property on the DomainClient."); 
       } 
       ChannelFactory factory = (ChannelFactory)channelFactoryProperty.GetValue(proxyInstance, null); 
       factory.Endpoint.Binding.SendTimeout = new TimeSpan(0, 10, 0); 
       factory.Endpoint.Binding.OpenTimeout = new TimeSpan(0, 10, 0); 
       factory.Endpoint.Binding.ReceiveTimeout = new TimeSpan(0, 10, 0); 
       factory.Endpoint.Binding.CloseTimeout = new TimeSpan(0, 10, 0); 


       PropertyInfo channelFactoryPropert = proxyInstance.GetType().GetProperty("InnerChannel"); 
       System.ServiceModel.IClientChannel factor = (System.ServiceModel.IClientChannel)channelFactoryPropert.GetValue(proxyInstance, null); 
       factor.OperationTimeout.Add(new TimeSpan(0, 10, 0)); 
       factor.OperationTimeout = new TimeSpan(0, 10, 0); 

我試圖發送一個參數:XML文檔中的字符串

var proxyInstance = GetProxyInstance(ref compilerResults, "http://localhost:49854/ServicioPrueba.svc?wsdl", "IContratoPrueba"); 
       string operationName = "GetData";//Nombre de metodo a llamar 

       XmlDocument doc = new XmlDocument(); 
       doc.Load(@"C:\\pru.xml"); 
       string xmlString = doc.InnerXml; 

       var methodInfo = proxyInstance.GetType().GetMethod(operationName); 
       //int var = int.Parse(textBox1.Text); 
       object[] operationParameters = new object[] { xmlString }; 

     var invoke= methodInfo.Invoke(proxyInstance, BindingFlags.InvokeMethod, null, operationParameters, null); 

我在上面一行的錯誤。

在app.config代碼:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" /> 
    </startup> 
    <system.serviceModel> 
<bindings> 
    <basicHttpBinding> 
     <binding name="WCF1_IContratoPrueba" closeTimeout="00:10:00" 
      openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" 
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" 
      maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" 
      textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true" 
      messageEncoding="Text"> 
      <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
      maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> 
     </binding> 
    </basicHttpBinding> 
</bindings>    
    <behaviors> 
     <endpointBehaviors> 
     <behavior name="PruebaWCF"> 
<dataContractSerializer 
maxItemsInObjectGraph="2147483647" /> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    </system.serviceModel> 
<system.diagnostics> 
    <sources> 
     <source name="System.ServiceModel" 
      switchValue="Critical,Information,ActivityTracing" 
       propagateActivity="true"> 
     <listeners> 
       <add name="messages" 
       type="System.Diagnostics.XmlWriterTraceListener" 
       initializeData="c:\messages.svclog" /> 
      </listeners> 
     </source> 
    </sources> 
    <trace autoflush="true" /> 
    </system.diagnostics> 
</configuration> 

在服務器的Web.config:

<?xml version="1.0"?> 
<configuration> 

    <appSettings> 
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> 
    </appSettings> 
    <system.web> 
    <compilation debug="true" targetFramework="4.0" /> 
    <!--<httpRuntime targetFramework="4.5"/>--> 
    <httpRuntime maxRequestLength="1048576" requestPathInvalidCharacters="" /> 
    </system.web> 

    <system.serviceModel> 
    <services> 
     <service name="WCF1.ServicioPrueba"> 
     <endpoint address="ServicioPrueba.svc" behaviorConfiguration="PruebaWCF" 
      binding="basicHttpBinding" bindingConfiguration="WCF1_IContratoPrueba" 
      name="ServicioPrueba" contract="WCF1.IContratoPrueba" /> 
     </service> 
    </services> 

    <behaviors> 
     <endpointBehaviors> 
       <behavior name="PruebaWCF"> 
     <dataContractSerializer 
     maxItemsInObjectGraph="2147483647" /> 
       </behavior> 
     </endpointBehaviors> 

     <serviceBehaviors> 
     <behavior> 
      <!-- To avoid disclosing metadata information, set the values below to false before deployment --> 
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/> 
      <!-- 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"/>--> 
      <serviceDebug includeExceptionDetailInFaults="true" /> 
      <dataContractSerializer maxItemsInObjectGraph="2147483647" /> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    <protocolMapping> 
     <add binding="basicHttpsBinding" scheme="https" />  
    </protocolMapping> 


    <bindings> 
     <basicHttpBinding> 
      <binding name="WCF1_IContratoPrueba" closeTimeout="00:10:00" 
       openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" 
       maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" 
       textEncoding="utf-8" transferMode="Streamed" messageEncoding="Text"> 
       <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
       maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> 
      </binding> 
     </basicHttpBinding> 
    </bindings> 
    </system.serviceModel> 

    <system.webServer> 
    <httpProtocol> 
     <customHeaders> 
      <add name="Access-Control-Allow-Origin" value="*" /> 
      <add name="Access-Control-Allow-Credentials" value="true" /> 
      <add name="Access-Control-Allow-Methods" value="POST,GET" /> 
      <add name="Access-Control-Allow-Headers" value="X-Requested-With,X-Prototype-Version,Content-Type,Cache-Control,Pragma,Origin" /> 
      <add name="Access-Control-Max-Age" value="1728000" /> 
      <add name="Access-Control-Expose-Headers" value="Access-Control-Allow-Origin" /> 
     </customHeaders> 
    </httpProtocol> 

    <modules runAllManagedModulesForAllRequests="true"/> 
    <directoryBrowse enabled="true"/> 
    </system.webServer> 


<system.diagnostics> 
    <sources> 
     <source name="System.ServiceModel" 
      switchValue="Critical,Information,ActivityTracing" 
       propagateActivity="true"> 
     <listeners> 
       <add name="messages" 
       type="System.Diagnostics.XmlWriterTraceListener" 
       initializeData="c:\server.svclog" /> 
      </listeners> 
     </source> 
    </sources> 
    <trace autoflush="true" /> 
    </system.diagnostics> 

</configuration> 

服務器例外:

Server stack trace: 
    en System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding) 
    en System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) 
    en System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) 
    en System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) 
    en System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) 
    en System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) 
    en System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) 

Exception rethrown at [0]: 
    en System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) 
    en System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp;amp; msgData, Int32 type) 
    en IContratoPrueba.GetData(Object value) 
    en ContratoPruebaClient.GetData(Object value)</ExceptionString><InnerException><Exception><ExceptionType>System.Net.WebException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Error en el servidor remoto: (413) Request Entity Too Large.</Message><StackTrace> en System.Net.HttpWebRequest.GetResponse() 
    en System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)</StackTrace><ExceptionString>System.Net.WebException: Error en el servidor remoto: (413) Request Entity Too Large. 
    en System.Net.HttpWebRequest.GetResponse() 
    en System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)</ExceptionString></Exception></InnerException></Exception></InnerException></Exception></TraceRecord></DataItem></TraceData></ApplicationData></E2ETraceEvent> 

客戶例外:

{System.Reflection.TargetInvocationException: Se produjo una excepción en el destino de la invocación. ---> System.ServiceModel.ProtocolException: El servidor remoto devolvió una respuesta inesperada: (413) Request Entity Too Large. ---> System.Net.WebException: Error en el servidor remoto: (413) Request Entity Too Large. 
    en System.Net.HttpWebRequest.GetResponse() 
    en System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) 
    --- Fin del seguimiento de la pila de la excepción interna --- 

Server stack trace: 
    en System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding) 
    en System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) 
    en System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) 
    en System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) 
    en System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) 
    en System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) 
    en System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) 

Exception rethrown at [0]: 
    en System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) 
    en System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) 
    en IContratoPrueba.Process(String xml) 
    en ContratoPruebaClient.Process(String xml) 
    --- Fin del seguimiento de la pila de la excepción interna --- 
    en System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) 
    en System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) 
    en System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 
    en WinForm.Form1.button1_Click(Object sender, EventArgs e) en c:\Users\Stardoc\Desktop\WCF\WinFormCliente\WinForm\Form1.cs:línea 74 
    en System.Windows.Forms.Control.OnClick(EventArgs e) 
    en System.Windows.Forms.Button.OnClick(EventArgs e) 
    en System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) 
    en System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) 
    en System.Windows.Forms.Control.WndProc(Message& m) 
    en System.Windows.Forms.ButtonBase.WndProc(Message& m) 
    en System.Windows.Forms.Button.WndProc(Message& m) 
    en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) 
    en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) 
    en System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 
    en System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) 
    en System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) 
    en System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) 
    en System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) 
    en System.Windows.Forms.Application.Run(Form mainForm) 
    en WinForm.Program.Main() en c:\Users\Stardoc\Desktop\WCF\WinFormCliente\WinForm\Program.cs:línea 19} 

Thanks in advance. 
+0

你的問題沒有錯誤。捕獲異常詳細信息並將其添加到[編輯]。 – Will

+0

我把它。我有一個svclog文件來保存日誌,由服務器和客戶端 – Javysk

+0

這有幫助。您是否在WPF標籤中搜索了「請求實體太大」的問題?有很多,例如http://stackoverflow.com/questions/10122957/iis7-413-request-entity-too-large-uploadreadaheadsize它可能與您的有效載荷(請求)的大小有關太大了。您可以通過配置對此進行調整。祝你好運! – Will

回答

0

最後,我可以解決這個問題,我不需要app.config中的任何東西,wef.config配置了相同的代碼,並把這些行放在客戶端。

我只需要強制轉換ChannelFactory,然後強制轉換BasicHttpBinding並設置參數。

謝謝大家。

  var timeOut=new TimeSpan(0, 10, 0); 
      int timeOutInt = 2147483647; 
      PropertyInfo channelFactoryProperty = proxyInstance.GetType().GetProperty("ChannelFactory"); 
     if (channelFactoryProperty == null) 
     { 
      throw new InvalidOperationException("There is no ''ChannelFactory'' property on the DomainClient."); 
     } 
     ChannelFactory factory = (ChannelFactory)channelFactoryProperty.GetValue(proxyInstance, null); 
     factory.Endpoint.Binding.SendTimeout = timeOut; 
     factory.Endpoint.Binding.OpenTimeout = timeOut; 
     factory.Endpoint.Binding.ReceiveTimeout = timeOut; 
     factory.Endpoint.Binding.CloseTimeout = timeOut; 

     BasicHttpBinding _binding = (BasicHttpBinding)factory.Endpoint.Binding; 
     _binding.MaxBufferPoolSize = timeOutInt; 
     _binding.MaxBufferSize = timeOutInt; 
     _binding.MaxReceivedMessageSize = timeOutInt; 
     _binding.OpenTimeout = timeOut;