(ASP.NET)Stream.Write在服务器上失败但在开发机上工作 - 任何想法?

时间:2011-01-23 17:40:47

标签: asp.net http stream httpwebrequest filestream

我想知道是否有人遇到Stream.Write()的问题,它在dev(Windows 7)环境下运行但在服务器环境(Windows 2008 R2 Enterprise)下失败?

我基本上使用的是一些从FileStream读取并写入Http请求的第三方代码,没什么不寻常的,它正在执行以下操作:

确保Response.KeepAlive为false(原来是真的但是W7工作而不是W2K8所以尝试了错误,但它似乎没有帮助); 确保Write包含要写入的字节长度; 确保我之后冲洗流;

我遇到的错误是相当含糊的“请求已中止:请求被取消了。”使用InnerException'在写入所有字节之前无法关闭流。'。现在,我的代码在Windows 7下完美运行,所以我仍然怀疑某些东西正在积极地阻止这种写作,尽管我不确定是什么,如何以及在哪里。

我想知道的另一种可能性是Windows Server 2008 R2下的编码可能与Windows 7不同吗?

以下是相关方法的代码片段(有点令人费解,但免责声明,我没有写出来: - ):

  string boundary = string.Concat("-------------------------", DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture));
  byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(string.Concat("\r\n--", boundary, "\r\n"));
  byte[] endBoundaryBytes = System.Text.Encoding.UTF8.GetBytes(string.Concat("\r\n--", boundary, "--\r\n"));

  List<byte> requestData = new List<byte>();
  requestData.AddRange(boundaryBytes);
  requestData.AddRange(System.Text.Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "Content-Disposition: form-data; name=\"key\"\r\n\r\n{0}", this.ApiKey)));
  if (methodAttribute.IsSessionRequired)
  {
    requestData.AddRange(boundaryBytes);
    requestData.AddRange(System.Text.Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "Content-Disposition: form-data; name=\"sessionid\"\r\n\r\n{0}", this.SessionId)));
  }
  if (endPoint != null && !string.IsNullOrEmpty(endPoint.Token))
  {
    requestData.AddRange(boundaryBytes);
    requestData.AddRange(System.Text.Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "Content-Disposition: form-data; name=\"token\"\r\n\r\n{0}", endPoint.Token)));
  }

  if (parameters != null && parameters.Keys.Count > 0)
  {
    foreach (string key in parameters.Keys)
    {
      string queryData = string.Format(CultureInfo.InvariantCulture, "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}", key, parameters[key]);
      requestData.AddRange(boundaryBytes);
      requestData.AddRange(System.Text.Encoding.UTF8.GetBytes(queryData));
    }
  }

  long fileSize = endBoundaryBytes.Length;

  if (fileStream != null)
  {
    string mimeType = StaticHelperFunctions.GetMimeType(fileStream);
    fileStream.Position = 0;
    if (string.IsNullOrEmpty(fileName))
    {
      fileName = DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
    }
    requestData.AddRange(boundaryBytes);
        requestData.AddRange(System.Text.Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n", fileName, mimeType)));
    fileSize += fileStream.Length;
  }

  try
  {

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestPath.ToString());
    request.Method = "POST";
    request.ContentType = string.Concat("multipart/form-data; boundary=", boundary);
    request.UserAgent = string.Concat("Microsoft .NET, ", this.GetType().Assembly.FullName);
    request.AllowWriteStreamBuffering = false;
    request.Accept = "text/xml";
    request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
    request.KeepAlive = false;
    request.Timeout = int.MaxValue;
    request.ReadWriteTimeout = int.MaxValue;
    request.ContentLength = requestData.Count + fileSize;

    bool isCancel = false;
    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(requestData.ToArray(), 0, requestData.Count);
        requestStream.Flush();

        if (fileStream != null)
        {
            byte[] buffer = new byte[32768];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                requestStream.Write(buffer, 0, bytesRead);
                requestStream.Flush();

                if (this.Uploading != null)
                {
                    ThirdPartyEventArgs uploadEventArgs = 
                        new ThirdPartyEventArgs(
                            typeof(ContractType), 
                            fileStream.Length, 
                            fileStream.Position);

                    this.Uploading(this, uploadEventArgs);
                    if (uploadEventArgs.Cancel)
                    {
                        isCancel = true;
                        request.Abort();
                        break;
                    }
                }
            }
        }
        if (!isCancel)
        {
           requestStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
           requestStream.Flush();
        }
    }

2 个答案:

答案 0 :(得分:0)

这可能是由以下原因引起的:

  • 在stream.close
  • 之前丢失Stream.Flush
  • 内容长度不正确
  • 权限差异

答案 1 :(得分:0)

我建议你检查一下你的requestPath。