我正在使用.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'
。
我做错了什么?
答案 0 :(得分:0)
您看到此行为的原因是因为响应流已在其他地方使用过。
如果要多次读取流,请先将其内容复制到MemoryStream
。然后,您可以根据需要随时阅读MemoryStream
。