Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to dispose an HttpResponseException from Request.CreateResponse()?

I have this code within a request handling method of an ApiController:

if (uri != null)
{
    HttpResponseMessage r = Request.CreateResponse(HttpStatusCode.Redirect);
    r.Headers.Location = uri;
    throw new HttpResponseException(r);
}

The potential problem is that "r" is never disposed (in my code at least).
I could wrap this in a using, but then wouldn't "r" get disposed before the response is streamed to the client?

What is the correct way to handle this?

like image 841
noctonura Avatar asked Dec 19 '13 18:12

noctonura


2 Answers

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.

like image 196
Erik Philips Avatar answered Oct 28 '22 17:10

Erik Philips


For me, "Instance is disposed elsewhere" doesn't means you don't need to deal with it.

My solution is RegisterForDispose so it becomes:

HttpResponseMessage r = Request.CreateResponse(HttpStatusCode.Redirect);
r.Headers.Location = uri;
this.request.RegisterForDispose(r);
throw new HttpResponseException(r);
like image 42
ChrisTorng Avatar answered Oct 28 '22 18:10

ChrisTorng