2014-08-28 36 views
1

我使用.Net Framework 4.0和C#开发ASP.NET MVC 4 web Api。我无法从HttpError读取responseStream

我在尝试从HttpError获得响应流时遇到了问题。

在这里,我产生HttpError

m_ExceptionLoggerHelper.LogException("ProductionOrderManagementController", "DoBatchPreparation", Singleton.AutomationServiceVM.COGErrors); 

HttpError myCustomError = new HttpError(Singleton.AutomationServiceVM.COGErrors) { { "CustomErrorCode", 4 } }; 
response = Request.CreateErrorResponse(HttpStatusCode.Conflict, myCustomError); 

随着小提琴手,我得到这个:

HTTP/1.1 409 Conflict 
Cache-Control: no-cache 
Pragma: no-cache 
Content-Type: application/json; charset=utf-8 
Expires: -1 
Server: Microsoft-IIS/8.0 
X-AspNet-Version: 4.0.30319 
X-SourceFiles: =?UTF-8?B?RDpcRnVlbnRlc1xBdXRvbWF0aW9uTWlkZGxld2FyZVxzcmNcQXV0b21hdGlvbk1pZGRsZXdhcmUuV2ViLkFwaVxhcGlccHJvZHVjdGlvbk9yZGVyc01hbmFnZW1lbnRcTUNHXzIwMTQwODI4MDgyOTQ4XGRvQmF0Y2hQcmVwYXJhdGlvbg==?= 
Persistent-Auth: true 
X-Powered-By: ASP.NET 
Date: Thu, 28 Aug 2014 06:32:36 GMT 
Content-Length: 70 

{"Message":"Preparation Failed SessionLocked\r\n","CustomErrorCode":4} 

在这里,我捕捉到了异常:

catch (WebException exception) 
{ 
    Stream responseStream = exception.Response.GetResponseStream(); 
    using (var reader = new StreamReader(responseStream)) 
    { 
     string result = reader.ReadToEnd(); 
     Console.WriteLine("Exception: " + result); 
    } 
} 

我有问题这里,new StreamReader(responseStream),因为我得到一个ArgumentException。在调试时,我检查了responseStream,我发现CanRead属性是错误的。

'responseStream.Length' throw an excepción type 'System.ObjectDisposedException'

我在做什么错?

+1

您看到此行为,因为该流已被其他地方读取。 – 2014-08-28 06:52:19

+0

@RobbyCornelissen是的,你是对的。谢谢。 – VansFannel 2014-08-28 06:55:38

+0

不客气。我将添加它作为答案。 – 2014-08-28 06:59:41

回答

0

您看到此行为的原因是因为响应流已在别处被使用。

如果要多次读取流,请首先将其内容复制到MemoryStream。然后,您可以随时阅读MemoryStream