Wcf большой файл данных - PullRequest
0 голосов
/ 29 января 2019

Я пытаюсь загрузить файл изображения в формате base64 из углового приложения.Приложение работает нормально для небольших изображений, но wcf выдает ошибку слишком большой ошибки для изображений размером более 200 КБ.Мой файл webconfig выглядит следующим образом.

<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=LAPTOP-7JC2DRGE;Integrated Security=true;Initial Catalog=ExamDB" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1"/>
    <httpRuntime targetFramework="4.6.1" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
    <membership>
      <providers>
        <clear />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager enabled="true">
      <providers>
        <clear />
        <add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
        <add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
      </providers>
    </roleManager>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehaviors">
          <!-- To avoid disclosing metadata information, set the values below to false 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" >
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="ExamService.ExamService" behaviorConfiguration="serviceBehaviors">
        <endpoint address="" contract="ExamService.IExamService" binding="webHttpBinding" behaviorConfiguration="web" ></endpoint>
      </service>
    </services>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https"  />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
        preCondition="managedHandler"/>
    </modules>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>

</configuration>

Я пробовал предыдущие ответы на этом сайте, но, похоже, ни один из них не работает.Я использую фреймворк 4.6.

1 Ответ

0 голосов
/ 29 января 2019

Я подозреваю, что вам нужно добавить элемент привязки для привязки webHttpBinding и установить для maxReceivedMessageSize нечто большее.Значение по умолчанию составляет 65536 байт.

Это необходимо установить в узле system.serviceModel в web.config

Ниже приведен пример xml, установленный на 5 МБ

<bindings>
  <webHttpBinding>
    <binding name="largeMessage" maxReceivedMessageSize="5000000" maxBufferPoolSize="5000000" maxBufferSize="5000000" closeTimeout="00:03:00" openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:03:00">
      <readerQuotas maxStringContentLength="5000000" maxArrayLength="5000000" maxBytesPerRead="5000000" />
      <security mode="None"/>
    </binding>
  </webHttpBinding>
</bindings>

Не могли бы вы попытаться обновить узел служб, чтобы явно использовать конфигурацию привязки (атрибут bindingConfiguration равен атрибуту имени привязки).Я не думаю, что это действительно необходимо, поскольку существует только одна привязка, но давайте попробуем быть явным.

<services>
  <service name="ExamService.ExamService" behaviorConfiguration="serviceBehaviors">
    <endpoint address="" contract="ExamService.IExamService" binding="webHttpBinding" bindingConfiguration="largeMessage" behaviorConfiguration="web" ></endpoint>
  </service>
</services>

ОБНОВЛЕНИЕ

Не уверен, что здесь происходит.Я сделал быструю фиктивную службу для репликации проблемы.

namespace LargeMessageService
{
    [ServiceContract]
    public interface ILobService
    {

        [OperationContract]
        [WebGet]
        string EchoWithGet(string s);

        [OperationContract]
        [WebInvoke]
        string EchoWithPost(string s);
    }

    public class LobService : ILobService
    {
        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }

        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }
    }
}

Когда у меня была конфигурация без определения привязки, она потерпела неудачу с 413, как вы видите.Когда я добавил привязку, это сработало.Мой полный файл web.config с привязкой:

<appSettings>
  <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
  <compilation debug="true" targetFramework="4.6.1" />
  <httpRuntime targetFramework="4.6.1"/>
</system.web>
<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="serviceBehaviors">
        <!-- To avoid disclosing metadata information, set the values below to false 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="true"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="web" >
        <webHttp></webHttp>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <bindings>
    <webHttpBinding>
      <binding name="largeMessage" maxReceivedMessageSize="5000000" maxBufferPoolSize="5000000" maxBufferSize="5000000" closeTimeout="00:03:00" openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:03:00">
        <readerQuotas maxStringContentLength="5000000" maxArrayLength="5000000" maxBytesPerRead="5000000" />
        <security mode="None"/>
      </binding>
    </webHttpBinding>
  </bindings>
  <services>
    <service name="LargeMessageService.LobService" behaviorConfiguration="serviceBehaviors">
      <endpoint address="" contract="LargeMessageService.ILobService" binding="webHttpBinding" bindingConfiguration="largeMessage" behaviorConfiguration="web" ></endpoint>
      <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
    </service>
  </services>
  <protocolMapping>
    <add binding="basicHttpsBinding" scheme="https"  />
  </protocolMapping>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true"/>
  <!--
      To browse web app root directory during debugging, set the value below to true.
      Set to false before deployment to avoid disclosing web app folder information.
    -->
  <directoryBrowse enabled="true"/>
</system.webServer>

Я использовал IISExpress и вызывал его через Postman, вызывая операцию EchoWithPost с xml.

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello</string>

заменив 'Hello' большой строкой (приблизительно 500K)

Попробуйте заставить это работать, и если это попытка выяснить разницу между этим и вашим,Дайте мне знать, как вы поживаете.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...