English 中文(简体)
Does ServiceStack support binary responses?
原标题:

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.

最佳回答

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.

问题回答

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();
    }
}

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!





相关问题
Does ServiceStack support binary responses?

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.

How do you implement authentication in servicestack.net

I m investigating servicestack.net - but it s examples and articles don t seem to cover authentication - is this something handled by servicestack.net - and if so how? In particular I m interested in ...

Redis Expire does not work

I use ServiceStack.Redis (build from the latest sources: https://github.com/ServiceStack/ServiceStack.Redis/tree/master/src). I do something like this: CacheRecord foundKey = cacheRecords.GetById(...

ServiceStack: how to deal with errors?

I m using ServiceStack with great results so far, except that dealing with errors is seemingly tricky. If something goes wrong during serialization of a message (because I forgot to add a default ...

ServiceStack.Text JSON parsing on .Net 4.0

H chaps, I am trying to use ServiceStack.Text for JSON parsing (it seems to be performing better than JSON.Net in various benchmarks I have seen). But I am not getting the results I am expecting. The ...

热门标签