gpt4 book ai didi

asp.net-mvc - 从操作写入输出流

转载 作者:行者123 更新时间:2023-12-02 00:14:09 25 4
gpt4 key购买 nike

由于一些奇怪的原因,我想将 HTML 从 Controller 操作直接写入响应流。(我理解MVC分离,但这是一个特例。)

我可以直接写入 HttpResponse 流吗?在这种情况下, Controller 操作应返回哪个 IView 对象?我可以返回“null”吗?

最佳答案

我使用从 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);
}
}

Controller 方法现在如下所示:

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

关于asp.net-mvc - 从操作写入输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/943122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com