Get Image as stream or byte array using OpenRasta
Would anyone be able to give me a quick 开发者_如何学Cpointer as to how I can get an OpenRasta handler that returns a byte array. To be exposed in the ResourceSpace without it being a JSON or XML object. i.e. I don't want it transcoded, I just want to be able to set the media type to "image/PNG" or similar.
Using ASP.Net MVC I can do it using a FileContentResult by returning
File(myByteArray, "image/PNG");
I just need to know the OpenRasta equivalent.
Thanks
You can just return a byte array as part of your handlerm but that will end up being served as application/octet-stream.
If you want to return files, you can simply return an implementation of IFile.
public class MyFileHandler {
public IFile Get(int id) {
var mybytes = new byte[];
return new InMemoryFile(new MemoryStream(mybytes)) {
ContentType = new MediaType("image/png");
}
}
}
You can also set the FileName property to return a specific filename, which will render a Content-Disposition header for you.
I looked this up on the OpenRasta mailing list and there were a couple of related posts: http://groups.google.com/group/openrasta/browse_thread/thread/5ae2a6d653a7421e# http://groups.google.com/group/openrasta/browse_thread/thread/a631d3629b25b88a#
I have got it going with the following sample:
Configuration:
ResourceSpace.Has.ResourcesOfType<IFile>()
.AtUri("/customer/{id}/avatar")
.HandledBy<CustomerAvatarHandler>();
Handler:
public class CustomerAvatarHandler
{
public object Get(int id)
{
const string filename = @"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Sunset.jpg";
return new InMemoryFile(File.OpenRead(filename));
}
}
Well there are some Stream codecs out there, but you can do it as simply as this
ResourceSpace.Has.ResourcesOfType<byte[]>()
.AtUri("/MyImageUri")
.HandledBy<ImageHandler>();
where Image handler returns a byte array made from a System.Drawing.Graphics object in my case.
Any other answers that shed more light on this topic would be appreciated.
精彩评论