异常(System.Reflection.targetInvocationException)通过WCF请求



我有一个错误,当我通过其他Proyect中的反射从WindowsForm发送一个大字符串到WCF。我看到我需要在web.config中将一些参数放在服务器和app.config中。我做到了,但我有同样的例外。同样,当我生成实例时,我将任何C#代码的行都放在客户端中。C#

中的代码
   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:UsersStardocDesktopWCFWinFormClienteWinFormForm1.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:UsersStardocDesktopWCFWinFormClienteWinFormProgram.cs:línea 19}
Thanks in advance.

最后,我可以解决此问题,我在app.config中不需要任何内容,wef.config配置了相同的代码,并将此行放入客户端。

我只需要施放通道,然后施放basichtpbinding并设置参数。

谢谢大家。

            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;

相关内容

  • 没有找到相关文章

最新更新