简体   繁体   中英

object 'new HttpResponseMessage()' is not disposed along all exception paths

I have tired using statement after going through the links in stackoverflow but still couldnt figure the exact solution.

 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;
                }
            }

getting the following error

CA2000 In method 'GetStyleSheet()', object 'new HttpResponseMessage()' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'new HttpResponseMessage()' before all references to it are out of scope.

The problem is that when creating the HttpResponseMessage you use a property initializer in addition to the constructor:

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

This leads to a code similar to the following is generated:

var httpRepsonseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(stream);
try
{
   // ...
}
finally
{
  httpResponseMessage.Dispose();
}

As you can see, httpResponseMessage will not be disposed if something goes wrong when creating the StreamContent and assigning it.

In order to solve this, move the assignment into the using block:

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

This way, the disposal takes place even if there is a problem when assigning the content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM