在C#net 4.0中尝试Stream.Write多次时出错

问题描述 投票:0回答:1
    string CRLF = "\r\n";
    string boundary = "--" + DateTime.Now.Ticks.ToString("x") + "--";
    byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes(CRLF + boundary + CRLF);
    string content_Type = "multipart/form; boundary=" + boundary +"; charset=UTF-8";

    request.Headers.Add("Authorization", "Bearer " + accessToken);  // 헤더 설정
    request.Headers.Add("consumerKey", consumerKey);
    request.Method = "POST";
    request.Date = DateTime.Now;
    request.ContentType = content_Type;

    Stream rs = request.GetRequestStream();

    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\""+CRLF+CRLF+"{1}";
    foreach (string key in param.Keys)
    {
        rs.Write(boundaryBytes, 0, boundaryBytes.Length);
        string formitem = string.Format(formdataTemplate, key, param[key]);
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        rs.Write(formitembytes, 0, formitembytes.Length);
        rs.Close();
    }
    rs.Write(boundaryBytes, 0, boundaryBytes.Length);

我在这里遇到错误。

    rs.Write(boundaryBytes, 0, boundaryBytes.Length);

错误详细信息

     System.Net.WebException was unhandled by user code
     HResult=-2146233079
     Message=The request has been aborted.The connection was closed unexpectedly.
     Source=System
      StackTrace:
     위치: System.Net.ConnectStream.InternalWrite(Boolean async, Byte[] buffer, Int32 offset, Int32 
     size, AsyncCallback callback, Object state)
     위치: System.Net.ConnectStream.Write(Byte[] buffer, Int32 offset, Int32 size)

   위치: Telerik.Web.UI.RadButton.OnClick(ButtonClickEventArgs e)
   위치: Telerik.Web.UI.RadButton.RaisePostBackEvent(String eventArgument)
   위치: Telerik.Web.UI.RadButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   위치: System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   위치: System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   위치: System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean 
  includeStagesAfterAsyncPoint)
  InnerException: 

我不明白的是10天前没有错误。

并且当rs.Write三次时,会发生错误。只需经过第二个。

c# asp.net-4.0 system.net.webexception
1个回答
1
投票
rs.Close();

例如,

foreach (string key in param.Keys)
{
    rs.Write(boundaryBytes, 0, boundaryBytes.Length);
    string formitem = string.Format(formdataTemplate, key, param[key]);
    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
    rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundaryBytes, 0, boundaryBytes.Length);
rs.Close();
© www.soinside.com 2019 - 2024. All rights reserved.