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

本文关键字:连接 主机 程主机 数据 传输 | 更新日期: 2023-09-27 17:56:58

我正在做一个文件上传项目,它是这样构建的:

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

  1. 周转基金服务

  2. "业务逻辑"的类库

  3. 用户界面

当我尝试上传大于 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 应用程序 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 运行它,也会发生这种情况。

也许我在某处忘记了一些配置,但我不知道在哪里......

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

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

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>