All the examples I've seen show that you do not have to dispose of the Response.
public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No product with ID = {0}", id)),
ReasonPhrase = "Product ID Not Found"
}
throw new HttpResponseException(resp);
}
return item;
}
Looking at the source code to HttpResponseException, it appears that it populates a Property (HttpResponseMessage Response
) with that value and disposing of it would probably cause the HttpResponseMessage either cause an ObjectDisposedException or fail to be delivered to the client.
You'll also notice that in the source code there is a SupressMessage:
[SuppressMessage("Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "Instance is disposed elsewhere")]
Instance is disposed of elsewhere (this is not referring to HttpResponseMesssage, it does not implement IDisposable).
What is the correct way to handle this?
I don't believe any change to your code is required.