1

通过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()”中,对象“new HttpResponseMessage()”未沿所有异常路径处理。在对对象“new HttpResponseMessage()”的所有引用超出范围之前调用 System.IDisposable.Dispose。

4

1 回答 1

0

问题是,在创建时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();
}

如您所见,httpResponseMessage如果在创建 StreamContent 并分配它时出现问题,将不会被释放。

为了解决这个问题,将赋值移动到 using 块中:

using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK))
{
  httpResponseMessage.Content = new StreamContent(stream);
  // ...
}

这样,即使在分配内容时出现问题,也会进行处置。

于 2017-12-05T08:00:54.347 回答