OutputStream is not available when a custom TextWriter is used

Topics: Customizing Orchard
Oct 1, 2015 at 5:26 AM
I encounter this error:

"OutputStream is not available when a custom TextWriter is used"

When trying to output a custom JPEG image using an action of a controller in a custom module.
public FileResult GetImage(Guid id) {
    Bitmap img = GenerateBitmap(id); // custom private method to generate
                                     // binary image data from id
    using(var memStream = new System.IO.MemoryStream()) {
        img.Save(memStream, ImageFormat.Jpeg);
        var result = new FileContentResult(memStream.GetBuffer(), "image/jpeg");
        return result;
HOWEVER, this error happened only if no user is logged in. When I'm logged in as administrator, the error didn't happen at all. This made me crazy.

Luckily, after working on it, I was inspired to hunt for .cs source code of FileContentResult. I found it here, create something similar to it, and use it instead in the above action method. Kinda like below:
public class HeadacheFileContentResult : FileResult {

    public FileContentResult(byte[] fileContents, string contentType) : base(contentType) {
        if (fileContents == null) {
            throw new ArgumentNullException("fileContents");

        FileContents = fileContents;
    public byte[] FileContents {
        private set;

    protected override void WriteFile(HttpResponseBase response) {
        var whatever = 0; // I put breakpoint here to see the 'response' object
        response.OutputStream.Write(FileContents, 0, FileContents.Length);

When watching (Shift+F9) the response object during breakpoint hit, I found out that accessing response.OutputStream throws the error, and response.Output has something in it that points to caching. Therefore, I googled how to disable caching explicitly for controller action methods, and surprise! Adding these attributes: [Themed, OutputCache(NoStore = true, Duration = 0)] before the action method fix everything!

I hope this battle story helps anyone who encounters something similar.

p.s.: HeadacheFileContentResult was scrapped afterward.