[英]I can't read a responseStream from a HttpError
我正在使用.Net Framework 4.0和C#開發ASP.NET MVC 4 Web Api。
當我嘗試從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);
有了Fiddler,我得到了:
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
屬性為false。
並且'responseStream.Length' throw an excepción type 'System.ObjectDisposedException'
。
我究竟做錯了什么?
您看到此行為的原因是,響應流已在其他地方使用。
如果要多次讀取流,請首先將其內容復制到MemoryStream
。 然后,您可以根據需要MemoryStream
讀取MemoryStream
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.