开发者

(ASP.NET) Stream.Write fails on server but works on dev machine - any ideas?

I was wondering whether anyone had encountered a problem with Stream.Write() where it works under a dev (Windows 7) environment but fails under a server environment (Windows 2008 R2 Enterprise)?

I'm basically working with some third party code which reads from a FileStream and writing to an Http request, nothing unusual and it's doing the following things:

Ensuring that Response.KeepAlive is false (was originally true but worked W7 and not W2K8 so tried false but it doesn't seem to help); Ensuring that the Write includes the length of the bytes to write; Ensuring that I Flush the stream afterwards;

The error that I encounter is the rather vague 'The request was aborted: The request was canceled.' with InnerException of 'Cannot close stream until all bytes are written.'. Now, my code works perfectly under Windows 7 so I still suspect that something is actively blocking this writing although I am not sure what, how and where.

One other possibility I wondered about was whether the encoding might be different under Windows Server 2008 R2 as opposed to Windows 7?

Here's a code snippet from the relevant method (a bit convoluted but, disclaimer, I didn't write it :-):

  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(bo开发者_StackOverflow社区undaryBytes);
        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();
        }
    }


This can be caused by:

  • Stream.Flush missing before stream.close
  • Incorrect content length
  • Differences in permissions


i suggest u check your requestPath.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜