"无法将数据写入传输连接:远程主机强行关闭现有连接。"

时间:2015-06-18 09:39:42

标签: c# wcf

我正在开发一个文件上传项目,它的构建如下:

我有一个包含多个项目的解决方案,其中一些是:

  1. WCF服务

  2. "业务逻辑"

  3. 的类库
  4. UI

  5. 当我尝试上传超过1MB的文件时,我收到此错误:

    "无法将数据写入传输连接:远程主机强行关闭现有连接。"

    以下是我上传文件的代码:

    public string UploadFile(string serviceUrl,decimal maxFileSize, AttachmentFileParams fileParams, Stream file)
            {
                try
                {
                    if (file.Length > (maxFileSize * 1024)) //maxFileSize is defined in KB and file.Length is in Bytes
                        return Serialization.ConvertToJson(new { IsError = true, ErrorMessage = Constants.Messages.MaxFileSizeExceeded + maxFileSize });
    
                    string requestUrl = string.Format("{0}/UploadFile", serviceUrl);
                    string jsonFile = Serialization.ConvertToJson(fileParams);
                    byte[] jsonFileBytes = Encoding.UTF8.GetBytes(jsonFile);
                    byte[] len = BitConverter.GetBytes(jsonFileBytes.Length);
    
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
                    request.Method = "POST";
    
                    byte[] bufferRead = new byte[checked((uint)Math.Min(4096, (int)jsonFileBytes.Length + file.Length))];
                    int bytesReadCount;
    
                    request.ContentLength = (long)len.Length + (long)jsonFileBytes.Length + file.Length;               
    
                    using (Stream requestStream = request.GetRequestStream())
                    {
    
                        requestStream.Write(len, 0, len.Length);
    
                        //*************************HERE IS WHERE THE ERROR IS THROWN*********************************//
                        requestStream.Write(jsonFileBytes, 0, jsonFileBytes.Length);
                        //*************************HERE IS WHERE THE ERROR IS THROWN*********************************//
    
                        while ((bytesReadCount = file.Read(bufferRead, 0, bufferRead.Length)) > 0)
                        {
                            requestStream.Write(bufferRead, 0, bytesReadCount);
                        }
    
                        requestStream.Close();
                    }
    
                    HttpWebResponse resposne = (HttpWebResponse)request.GetResponse();
    
                    string result = string.Empty;
    
                    using (StreamReader reader = new StreamReader(resposne.GetResponseStream()))
                    {
                        result = reader.ReadToEnd();
                    }
                    return result;
                }
                catch (Exception ex)
                {
                    return Serialization.ConvertToJson(new { IsError = true, ErrorMessage = ex.Message });
                }
            }
    

    我试过在wcf服务和ui app web.config文件中添加这些配置:

    <system.web>
        <httpRuntime maxRequestLength="1073741824" executionTimeout="3600" />
    </system.web>
    
    <system.webServer>
        <security>
          <requestFiltering>
            <requestLimits maxAllowedContentLength="1073741824" />
          </requestFiltering>
        </security>
      </system.webServer>
    
    
    //in the service config file there is also this:
    <system.serviceModel>
        <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>
        <bindings>
          <wsHttpBinding>
            <binding name="WSHttpBinding_IBroadcast360" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647" receiveTimeout="00:01:00" sendTimeout="00:01:00"
                     textEncoding="utf-8" openTimeout="00:01:00" transactionFlow="True">
              <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
              <security mode="None" />          
            </binding>
          </wsHttpBinding>
        </bindings>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
      </system.serviceModel>
    

    我不认为这与服务器问题有关,因为即使我在本地计算机上使用VisualStudio运行它,我也会发生这种情况。

    也许我在某个地方忘记了一些困惑,但我不知道在哪里......

1 个答案:

答案 0 :(得分:0)

我解决了,这是解决方案的代码:

public class WCFClientProxy<IServiceContract> : ClientBase<IServiceContract> where IServiceContract : class
{
    public IServiceContract Instance
    {
        get { return base.Channel; }
    }
}

public string UploadFile(decimal maxFileSize, AttachmentFileParams fileParams, Stream file)
{
    try
    {
        if (file.Length > (maxFileSize * 1024)) //maxFileSize is defined in KB and file.Length is in Bytes
            return Serialization.ConvertToJson(new { IsError = true, ErrorMessage = Constants.Messages.MaxFileSizeExceeded + maxFileSize });

        string jsonFile = Serialization.ConvertToJson(fileParams);
        byte[] jsonFileBytes = Encoding.UTF8.GetBytes(jsonFile);
        byte[] len = BitConverter.GetBytes(jsonFileBytes.Length);
        byte[] bufferRead = new byte[checked((uint)Math.Min(4096, (int)jsonFileBytes.Length + file.Length))];
        int bytesReadCount;

        using (Stream stream = new MemoryStream())
        {
            stream.Write(len, 0, len.Length);
            stream.Write(jsonFileBytes, 0, jsonFileBytes.Length);

            while ((bytesReadCount = file.Read(bufferRead, 0, bufferRead.Length)) > 0)
            {
                stream.Write(bufferRead, 0, bytesReadCount);
            }
            stream.Position = 0;
            WCFClientProxy<Attachment.Interfaces.IAttachmentService> proxy = new WCFClientProxy<Attachment.Interfaces.IAttachmentService>();
            return proxy.Instance.UploadFile(stream);
        }
    }
    catch (Exception ex)
    {
        return Serialization.ConvertToJson(new { IsError = true, ErrorMessage = ex.Message });
    }
}

服务配置:

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime maxRequestLength="2147483647" executionTimeout="3600" />
  </system.web>

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="XXX.Implementation.AttachmentService">
        <endpoint binding="webHttpBinding"
                  behaviorConfiguration="webHttpBehavior"
                  bindingConfiguration="higherMessageSize"
                  contract="XXX.Interfaces.IAttachmentService" />
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="higherMessageSize" transferMode="Streamed" closeTimeout="10:00:00" openTimeout="10:00:00" receiveTimeout="10:00:00" sendTimeout="10:00:00"
                 maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 maxReceivedMessageSize="2147483647">

          <readerQuotas maxDepth="2147483647"
                        maxArrayLength="2147483647"
                        maxBytesPerRead="2147483647"
                        maxNameTableCharCount="2147483647"
                        maxStringContentLength="2147483647"/>

          <security mode="None"/>
        </binding>
      </webHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule"/>
    </modules>
     <handlers>
         <remove name ="WebDAV"/>
    </handlers>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483647" />
      </requestFiltering>
    </security>
  </system.webServer>

客户端配置:

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime maxRequestLength="2147483647" />
  </system.web>

  <system.serviceModel>
    <bindings>
      <webHttpBinding>

        <binding name="WebHttpBinding_IAttachmentService" closeTimeout="10:00:00" openTimeout="10:00:00" receiveTimeout="10:00:00" sendTimeout="10:00:00"
                 maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 maxReceivedMessageSize="2147483647">

          <readerQuotas maxDepth="2147483647"
                        maxArrayLength="2147483647"
                        maxBytesPerRead="2147483647"
                        maxNameTableCharCount="2147483647"
                        maxStringContentLength="2147483647"/>

          <security mode="None" />
        </binding>
      </webHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:54893/AttachmentService.svc"
                binding="webHttpBinding"
                bindingConfiguration="WebHttpBinding_IAttachmentService"
                behaviorConfiguration="webHttpBehavior"
                contract="XXX.Interfaces.IAttachmentService" />
    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
  </system.webServer>