我有以下代码使用StreamWriter写入简单RESTfull调用的请求:
private T GetRestPutResult<T>(string restUri, string payload, Func<StreamReader, T> getResultFunc)
{
try
{
HttpWebRequest taskListRequest = (HttpWebRequest)ActMgmtWebRequest.Create(restUri);
taskListRequest.ContentType = ActivitiConstants.HttpRequest.ContentTypeApplicationJson;
taskListRequest.Method = ActivitiConstants.HttpRequest.MethodPut;
taskListRequest.Headers.Add("Authorization", "Basic " + serviceCredentials);
using (var streamWriter = new StreamWriter(taskListRequest.GetRequestStream()))
{
streamWriter.Write(payload);
using (WebResponse svcResponse = (HttpWebResponse)taskListRequest.GetResponse())
{
using (StreamReader sr = new StreamReader(svcResponse.GetResponseStream()))
{
return getResultFunc(sr); // <-line 171
}
}
}
}
catch (Exception ex)
{
throw new Exception(string.Format("The REST service (url: {0}) threw an exception.", restUri), ex);
}
}
我收到以下错误,因为返回被命中(它调用getResultFunc,它成功读取响应流,然后返回此方法并抛出此错误:
System.Net.WebException was caught
HResult=-2146233079
Message=The request was aborted: The connection was closed unexpectedly.
Source=System
StackTrace:
at System.Net.ConnectStream.InternalWrite(Boolean async, Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
at System.Net.ConnectStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.Dispose(Boolean disposing)
at System.IO.TextWriter.Dispose()
at Org.Intermountain.ActMgmt.ActivitiService.ActivitiWorkflowProxy.GetRestPutResult[T](String restUri, String payload, Func`2 getResultFunc) in c:\dev\ActMgmt\trunk\Org.Intermountain.ActMgmt.ActivitiService\ActivitiWorkflowProxy.cs:line 171
InnerException:
这看起来像编写器上的dispose方法导致了问题。
此时请求实际上已经成功,一切都很顺利。该服务甚至返回JSON响应,我从缓冲区获取它,并在getFuncResult方法中处理响应,该方法成功执行并向此方法返回一个布尔值,但是当我从此方法返回时,我收到此错误。我似乎已经关闭了当我使用streamWriter范围结束时请求已关闭所以当它处理它时会抛出错误。如何避免此错误?
我搜索了这个错误,但大多数评论是基于读者的,在那里找不到这样的东西。
提前致谢