I'm attempting to return a stream from my webapi endpoint, and then clean up by disposing the stream.
I expected this to be the correct way, but the stream is of course disposed before returning.
using(var stream = GetStream()){
var response = new HttpResponseMessage();
response.Content = new StreamContent(stream);
return response;
}
What will be the correct way of disposing the stream?
(Since MSDN says nothing about the behaviour of StreamContent or its methods, my temporary solution is to copy the contents of the stream to a byte array and return that.)
As your only resource that needs to be disposed is the Content of the HttpResponseMessage
you don't have to worry about it. The framework does the dispose for you. It will dispose the HttpResponseMessage
which will do all the disposing needed. Remove the using and it should work just fine.
The HttpResponseMessage will dispose its Content when it is disposed. See .NET Core implementation
The StreamContent will dispose its stream when it is disposed. See .NET Core implementation of StreamContent
If you need to dispose something not disposed by the HttpResponseMessage you may use request.RegisterForDispose
as described by Filip Woj
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With