从Action写入输出流

时间:2009-06-03 04:56:34

标签: asp.net-mvc

出于某些奇怪的原因,我想从控制器操作直接将HTML写入Response流。 (我理解MVC分离,但这是一个特例。)

我可以直接写入HttpResponse信息流吗?在这种情况下,控制器操作应返回哪个IView对象?我可以退回'null'吗?

5 个答案:

答案 0 :(得分:45)

我使用了从FileResult派生的类来使用普通的MVC模式实现这一点:

/// <summary>
/// MVC action result that generates the file content using a delegate that writes the content directly to the output stream.
/// </summary>
public class FileGeneratingResult : FileResult
{
    /// <summary>
    /// The delegate that will generate the file content.
    /// </summary>
    private readonly Action<System.IO.Stream> content;

    private readonly bool bufferOutput;

    /// <summary>
    /// Initializes a new instance of the <see cref="FileGeneratingResult" /> class.
    /// </summary>
    /// <param name="fileName">Name of the file.</param>
    /// <param name="contentType">Type of the content.</param>
    /// <param name="content">Delegate with Stream parameter. This is the stream to which content should be written.</param>
    /// <param name="bufferOutput">use output buffering. Set to false for large files to prevent OutOfMemoryException.</param>
    public FileGeneratingResult(string fileName, string contentType, Action<System.IO.Stream> content,bool bufferOutput=true)
        : base(contentType)
    {
        if (content == null)
            throw new ArgumentNullException("content");

        this.content = content;
        this.bufferOutput = bufferOutput;
        FileDownloadName = fileName;
    }

    /// <summary>
    /// Writes the file to the response.
    /// </summary>
    /// <param name="response">The response object.</param>
    protected override void WriteFile(System.Web.HttpResponseBase response)
    {
        response.Buffer = bufferOutput;
        content(response.OutputStream);
    }
}

控制器方法现在是这样的:

public ActionResult Export(int id)
{
    return new FileGeneratingResult(id + ".csv", "text/csv",
        stream => this.GenerateExportFile(id, stream));
}

public void GenerateExportFile(int id, Stream stream)
{
    stream.Write(/**/);
}

请注意,如果关闭缓冲,

stream.Write(/**/);

变得非常慢。解决方案是使用BufferedStream。这样做可以在一种情况下将性能提高大约100倍。参见

Unbuffered Output Very Slow

答案 1 :(得分:9)

是的,您可以直接写回应。完成后,您可以调用CompleteRequest(),您不需要返回任何内容。

例如:

// GET: /Test/Edit/5
public ActionResult Edit(int id)
{

    Response.Write("hi");
    HttpContext.ApplicationInstance.CompleteRequest();

    return View();     // does not execute!
}

答案 2 :(得分:5)

编写自己的行动结果。以下是我的一个例子:

public class RssResult : ActionResult
{
    public RssFeed RssFeed { get; set; }

    public RssResult(RssFeed feed) {
        RssFeed = feed;
    }

    public override void ExecuteResult(ControllerContext context) {
        context.HttpContext.Response.ContentType = "application/rss+xml";
        SyndicationResourceSaveSettings settings = new SyndicationResourceSaveSettings();
        settings.CharacterEncoding = new UTF8Encoding(false);
        RssFeed.Save(context.HttpContext.Response.OutputStream, settings);
    }
}

答案 3 :(得分:4)

如果您不想派生自己的结果类型,只需写信至Response.OutputStream并返回new EmptyResult()

答案 4 :(得分:3)

您可以执行return Content(...);,如果我没记错的话,...将是您想要直接写入输出流的内容,或者根本没有内容。

查看Content上的Controller方法:http://aspnet.codeplex.com/SourceControl/changeset/view/22907#266451

ContentResulthttp://aspnet.codeplex.com/SourceControl/changeset/view/22907#266450