This project is read-only.

Dispose pattern and disposal responsibility for HttpRequestMessage and HttpResponseMessage

Topics: ASP.NET Web API, General
Oct 8, 2013 at 10:54 AM
Edited Oct 8, 2013 at 11:01 AM

So what is the design principle for disposing HttpRequestMessage and HttpResponseMessage? I have not seen anywhere a requirement or a sample including disposing of request or response.

My understanding is that the framework is responsible for disposing these resources but I have hit an issue when dealing with HttpClient when I replace the response in the HTTP pipeline and this results in socket and memory leak.

I believe this could be regarded as a bug in the framework since the HttpClient should register original response for disposal regardless of what response is returned.

So what are your views? I have fell victim to this and I am sure more to come as we use Web API more and more in production.
Oct 8, 2013 at 5:42 PM
The person consuming the request or response should dispose of it when they are done with it (success or failure). E.g. HttpClient disposes of request messages after it sends them. The caller should dispose any HttpResponseMessage returned to them. The framework has no way to know when you are done with the response.

Since you are replacing the response you need to dispose of the prior one.

On a more practical note, requests and responses are only disposable because they own an HttpContent. The actual need to call dispose on HttpContent varies by implementation. For example, StringContent doesn't need any cleanup, so not calling dispose is OK. However, StreamContent may need to be disposed depending on the Stream. In the most common case the response message content is a StreamContent where the Stream is attached to a Socket. The full response body must be consumed, or the StreamContent, Stream, and Socket must be disposed. HttpClient consumes and buffers response bodies by default, disposing the underlying Stream, so most people don't have to worry about disposing the response message/content. However, when you disable or bypass this behavior you become responsible for making sure the content gets consumed and/or disposed.
Oct 9, 2013 at 8:48 AM
Thank you. So what is the pattern on the server? Is there any disposal needed or framework takes care of it?
Oct 9, 2013 at 3:09 PM

Web API’s hosting layers(Ex: HttpControllerHandler in case of Webhost, HttpMessageHandlerAdapter in case of Owin selfhost) take care of disposing the request and response messages.

Oct 9, 2013 at 3:44 PM
On the server intermediate handlers are still required to dispose response messages that they replace. The framework can only dispose the final response message. There not sure about the request message, but that should only matter for uploads.