Search code examples
c#filereststreaming

C# Serving a stream to a browser - can it be done?


I am trying to output a file to the browser from a REST API - but I don't have a physical file, instead I have a MemoryStream (and I would prefer not to write a physical file).

This works:

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
result.Content = new StreamContent(stream);
return result;

This does not:

var stream = new MemoryStream();

// Iterate DataReader and populate MemoryStream code omitted for brevity.
// Assume MemoryStream has been written to correctly and contains data.

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
return result;

This has consumed most of my weekend so I would be delighted if anyone can offer some definitive insight.


Solution

  • I've found the answer through trial and error and a lot of research:

    Yes, it can be done.

    Instead of using StreamContent use ByteArrayContent: e.g.

    result.Content = new ByteArrayContent( stream.GetBuffer() );
    

    Ensure that there is no HttpResponseMessage.ContentLength set or it will fail to work (connection reset) - it took me hours to figure that out.