对象'new HttpResponseMessage()'未沿所有异常路径放置

时间:2017-12-05 07:52:33

标签: c# asp.net-web-api asp.net-web-api2 dispose httpresponsemessage

在浏览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()'未沿所有异常路径放置。在对所有引用超出范围之前,调用System.IDisposable.Dispose对象'new HttpResponseMessage()'。

1 个答案:

答案 0 :(得分: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();
}

如您所见,如果在创建StreamContent并分配时出现问题,则不会处理httpResponseMessage

为了解决这个问题,请将分配移动到使用块:

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

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