Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ServiceStack support binary responses?

Tags:

servicestack

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.

like image 927
Sebastian Good Avatar asked Jun 05 '11 20:06

Sebastian Good


2 Answers

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();
    }
}
like image 181
ruslander Avatar answered Nov 01 '22 11:11

ruslander


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.

like image 16
mythz Avatar answered Nov 01 '22 13:11

mythz