I'm trying to async stream a file from sql server out to a web client using .net 4.5 and web api.
I'm using SqlDataReader.GetStream() to get a stream from the db. However, I'm not sure how to wire in the disposal/closing of the db connection when webapi is finished reading from the stream.
Any samples out there?
You can write a wrapping stream that reads from the underlying stream until it is depleted, and then disposes of all associated resources (like the SqlConnection).
I'm not a WebAPI expert so there might be a more elegant way to do it. But this will work in any case with the standard WebAPI support for streams.
You could do something like following in Web API. Here I am using
PushStreamContent
to connect to database and retrieve the Sql stream. I then copy this sql stream to the response stream directly. In Web API, when you use PushStreamContent, the client would receive response in chunked transfer encoding because you are not setting the content-length of the response. If this is fine for you, you could use the below example. Otherwise I will try to see if there are any other better ways to accomplish this.NOTE: This is a quick example based on PushStreamContent and this article on MSDN regarding retrieving binary data from sql server.