15

Is there any mechanism in ServiceStack services to return streaming/large binary data? WCF's MTOM support is awkward but effective in returning large amounts of data without text conversion overhead.

3 Answers 3

19

I love service stack, this litle code was enough to return an Excel report from memory stream

public class ExcelFileResult : IHasOptions, IStreamWriter
{
    private readonly Stream _responseStream;
    public IDictionary<string, string> Options { get; private set; }

    public ExcelFileResult(Stream responseStream)
    {
        _responseStream = responseStream;

        Options = new Dictionary<string, string> {
             {"Content-Type", "application/octet-stream"},
             {"Content-Disposition", "attachment; filename=\"report.xls\";"}
         };
    }

    public void WriteTo(Stream responseStream)
    {
        if (_responseStream == null) 
            return;

        _responseStream.WriteTo(responseStream);
        responseStream.Flush();
    }
}
3
  • Where does _responseStream.WriteTo come from ? It's not Stream method. Commented Nov 22, 2012 at 17:52
  • 2
    ServiceStack providers additional functionality as extension methods on many of the BCL classes. Stream.WriteTo is found at ServiceStack.Text.StreamExtensions.WriteTo. Commented Mar 10, 2013 at 22:34
  • 1
    IoC (Inversion of Control) (a.k.a DI - Dependency Injection) through constructor parameter.
    – George
    Commented Sep 25, 2013 at 16:22
16

From a birds-eye view ServiceStack can return any of:

  • Any DTO object -> serialized to Response ContentType
  • HttpResult, HttpError, CompressedResult (IHttpResult) for Customized HTTP response

The following types are not converted and get written directly to the Response Stream:

  • String
  • Stream
  • IStreamWriter
  • byte[] - with the application/octet-stream Content Type.

Details

In addition to returning plain C# objects, ServiceStack allows you to return any Stream or IStreamWriter (which is a bit more flexible on how you write to the response stream):

public interface IStreamWriter
{
    void WriteTo(Stream stream);
}

Both though allow you to write directly to the Response OutputStream without any additional conversion overhead.

If you want to customize the HTTP headers at the sametime you just need to implement IHasOptions where any Dictionary Entry is written to the Response HttpHeaders.

public interface IHasOptions
{
    IDictionary<string, string> Options { get; }
}

Further than that, the IHttpResult allows even finer-grain control of the HTTP output where you can supply a custom Http Response status code. You can refer to the implementation of the HttpResult object for a real-world implementation of these above interfaces.

2
  • So the basic concept is the same as the MTOM-like WCF services, where the raw binary (or whatever) response is the 'true' result of the service, and any other metadata must be returned in the headers. Commented Jun 6, 2011 at 19:07
  • Yep exactly, the stream is written to the ResponseStream as-is (i.e. inside no wrappers) and the metadata is written to the headers.
    – mythz
    Commented Jun 6, 2011 at 19:20
4

I had a similar requirement which also required me to track progress of the streaming file download. I did it roughly like this:

server-side:

service:

public object Get(FooRequest request)
{
    var stream = ...//some Stream
    return new StreamedResult(stream);
}

StreamedResult class:

public class StreamedResult : IHasOptions, IStreamWriter
{
    public IDictionary<string, string> Options { get; private set; }
    Stream _responseStream;

    public StreamedResult(Stream responseStream)
    {
        _responseStream = responseStream;

        long length = -1;
        try { length = _responseStream.Length; }
        catch (NotSupportedException) { }

        Options = new Dictionary<string, string>
        {
            {"Content-Type", "application/octet-stream"},
            { "X-Api-Length", length.ToString() }
        };
    }

    public void WriteTo(Stream responseStream)
    {
        if (_responseStream == null)
            return;

        using (_responseStream)
        {
            _responseStream.WriteTo(responseStream);
            responseStream.Flush();
        }
    }
}

client-side:

string path = Path.GetTempFileName();//in reality, wrap this in try... so as not to leave hanging tmp files
var response = client.Get<HttpWebResponse>("/foo/bar");

long length;
if (!long.TryParse(response.GetResponseHeader("X-Api-Length"), out length))
    length = -1;

using (var fs = System.IO.File.OpenWrite(path))
    fs.CopyFrom(response.GetResponseStream(), new CopyFromArguments(new ProgressChange((x, y) => { Console.WriteLine(">> {0} {1}".Fmt(x, y)); }), TimeSpan.FromMilliseconds(100), length));

The "CopyFrom" extension method was borrowed directly from the source code file "StreamHelper.cs" in this project here: Copy a Stream with Progress Reporting (Kudos to Henning Dieterichs)

And kudos to mythz and any contributor to ServiceStack. Great project!

Not the answer you're looking for? Browse other questions tagged or ask your own question.