I have an ASP.NET MVC 4 Web Api controller method that gets passed a list of file IDs and returns thumbnail images for those files.
So, the client might pass in a list of numeric IDs (e.g. 10, 303, 29), and the method returns a List where a ThumbnailImage looks a bit like this:
class ThumbnailImage
{
public int Id { get; set; }
// Some other stuff
public byte[] RawData { get; set; }
}
The reason that the caller passes in a list of IDs rather than making one call per item should hopefully be obvious - there may be dozens or hundreds of items to download, and I'm trying to avoid all the HTTP traffic that would be required to download them individually.
Currently, I'm using RestSharp and JSON.NET, and so my ThumbnailImage objects are being passed across the wire as JSON. It's fine from a simplicity-of-coding point of view, but JSON is not an efficient way to represent that binary data.
So, I'm thinking that I should return the raw bytes as an octet-stream... however, while I can easily do that for a single image, I'm not sure of the best way to do it for multiple images, especially when I also need to return the ID and miscellaneous other information for each file. (The ID is required since the results will not necessarily be returned in a given order - and some files may be missing).
I could simply write everything piecemeal into the response stream, so that for each item I write the ID (suitably encoded), followed by the length of the image data, followed by the image data itself, and then followed by the same thing for the next item, etc.
The caller would then simply keep reading from the stream until it was exhausted, making assumptions about the encoding (and length!) of the IDs, etc.
I think that would work, but it seems clunky - is there a better way?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…