我在浏览stackoverflow中的链接后使用语句感到疲倦,但仍然无法弄清楚确切的解决方案。
using (MemoryStream stream = new MemoryStream(textAsBytes))
{
using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
})
{
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "main-theme.scss"
};
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/css");
ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);
return responseMessageResult;
}
}
获取以下错误
ca2000在方法'getStylesHeet()',对象'新的httpresponsemessage()'中'并未按照所有异常路径处置。在对象"新的httpresponsemessage()"上call system.idisposable.dispose在所有引用均超出范围之前。
问题是,在创建HttpResponseMessage
时,您还使用属性初始化器,而不是构造函数:
using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
})
{
// ...
}
这将产生类似于以下代码的代码:
var httpRepsonseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(stream);
try
{
// ...
}
finally
{
httpResponseMessage.Dispose();
}
如您所见,如果在创建流content并分配它时出现问题,则httpResponseMessage
不会被处置。
为了解决这个问题,请将分配移至使用块中:
using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK))
{
httpResponseMessage.Content = new StreamContent(stream);
// ...
}
以这种方式,即使分配内容时存在问题。