2014-08-28 40 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