Подтвердить что ты не робот

Удаленный сервер возвратил неожиданный ответ: (413) Request Entity Too Large.

Я пытаюсь создать службу приложений WCF, используя FW4.0. Моя служба работает правильно при передаче объекта EntiryFramework между сервером и клиентом. Но у меня проблема с отправкой объекта EF из Client to Server.

Вот более подробная информация о моей среде: - Служба работает в режиме отладки локально на IIS - Я запускаю все это на своей Windows 7 - Я использую Visual Studio 2010 на FW4.0

Я пытаюсь отправить объект (tblClient) на сервер, чтобы сохранить запись, но сохранить с ошибкой (413) Request Entity Too Large. Здесь полный стек:

System.ServiceModel.ProtocolException occurred
      HResult=-2146233087
      Message=The remote server returned an unexpected response: (413) Request Entity Too Large.
      Source=mscorlib
      StackTrace:
        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 ClientApp.ServiceReference1.IService.SaveClient(tblClient client)
           at ClientApp.ServiceReference1.ServiceClient.SaveClient(tblClient client) in C:\dufh\WPF Project\ClientApp\Service References\ServiceReference1\Reference.vb:line 2383
           at ClientApp.ViewModel.ClientViewModel.SaveClient() in C:\dufh\WPF Project\ClientApp\ViewModel\ClientViewModel.vb:line 48
      InnerException: System.Net.WebException
           HResult=-2146233079
           Message=The remote server returned an error: (413) Request Entity Too Large.
           Source=System
           StackTrace:
                at System.Net.HttpWebRequest.GetResponse()
                at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
           InnerException:

У меня есть некоторые исследования, и все указывает на maxBufferSize и/или maxBufferPoolSize и/или maxReceivedMessageSize, ведьма недостаточно велика в конфигурации клиента App.Config. Поэтому я наложил их на максимальное значение: maxBufferSize = "2147483647" maxBufferPoolSize = "2147483647" maxReceivedMessageSize = "2147483647" Но все же ошибка остается.

Здесь мой полный клиент App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <sources>
      <!-- This section defines the logging configuration for My.Application.Log -->
      <source name="DefaultSource" switchName="DefaultSwitch">
        <listeners>
          <add name="FileLog"/>
          <!-- Uncomment the below section to write to the Application Event Log -->
          <!--<add name="EventLog"/>-->
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="DefaultSwitch" value="Information" />
    </switches>
    <sharedListeners>
      <add name="FileLog"
           type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
           initializeData="FileLogWriter"/>
      <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
      <add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="MVVM Sampling"/>
    </sharedListeners>
  </system.diagnostics>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:7803/Service1.svc" binding="basicHttpBinding"
          bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference1.IService"
          name="BasicHttpBinding_IService" />
    </client>
  </system.serviceModel>
</configuration>

и полный Web.Config WCF-сервис Web.Config

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

  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>

    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
          <readerQuotas maxDepth="200" maxStringContentLength="8388608" maxArrayLength="16384" maxBytesPerRead="2147483647" maxNameTableCharCount="16384" />
        </binding>
      </basicHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- 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>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />


  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <connectionStrings>
    <add name="MaitreEntities" connectionString="metadata=res://*/Schemat.csdl|res://*/Schemat.ssdl|res://*/Schemat.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=INFOFILE2\SQL2008R2;initial catalog=0001ConneryFerland;user id=sa;password=kermit80;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>


Any help would be very welcome :-)
4b9b3361

Ответ 1

Для записи

Я думаю, что понял. Web.Config из службы не имеет обязательной информации. Я поместил эту информацию в нее, и вуаля!

<bindings>
      <basicHttpBinding>
        <binding maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text">
          <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
        </binding>
      </basicHttpBinding>
</bindings>

Обратите внимание, что привязка не имеет указанного имени.

Ответ 2

У вас нет явной конечной точки (то есть определенной в вашем конфигурационном файле) для вашей службы, поэтому указанная вами конфигурация связывания ( "BasicHttpBinding_IService" ) не используется. WCF предоставляет конечную точку по умолчанию вместе с привязкой по умолчанию (basicHttpBinding, если вы не переопределите ее в разделе protocolMapping конфигурационного файла).

У вас есть два способа решить эту проблему в конфигурационном файле службы:

Вы можете настроить конфигурацию "BasicHttpBinding_IService" по умолчанию, удалив атрибут name:

<binding maxBufferPoolSize="2147483647".....

Или вы определяете конечную точку явно в конфигурации и назначаете свою конфигурацию привязки атрибуту bindingConfiguration конечной точки.

<services>
    <endpoint address="" 
              binding="basicHttpBinding"
              bindingConfiguration="BasicHttpBinding_IService"     
              contract="ServiceReference1.IService"  />
</services>

Ответ 3

Еще один способ исправить это и лучше просмотреть файл web.config - это отредактировать файл web.config с помощью "Microsoft Configuration Configuration Editor" (C:\Program Files (x86)\Microsoft SDK\Windows\v8.1A\bin\NETFX 4.5.1 Инструменты\SvcConfigEditor.exe)

Ответ 4

Если вы создаете пользовательскую привязку, например. MybasicBinding,

  <basicHttpBinding>
      <binding name="MybasicBinding" closeTimeout="01:00:00" openTimeout="01:00:00" receiveTimeout="01:00:00" sendTimeout="01:00:00"
               maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" >
            <readerQuotas maxDepth="32" maxBytesPerRead="200000000" 
             maxArrayLength="200000000" maxStringContentLength="200000000" />
      </binding>
  </basicHttpBinding>

Чтобы избежать ошибки 413, не указывайте bindingConfiguration = "MybasicBinding" для конечной точки службы как,

<endpoint address="" binding="basicHttpBinding" bindingConfiguration="MybasicBinding" contract="WCFService.IService" />