मैं इस का उपयोग कर सामान्य MVC पैटर्न प्राप्त करने के लिए एक वर्ग FileResult
से प्राप्त इस्तेमाल किया:
/// <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 का उपयोग करना है। एक मामले में लगभग 100x तक बेहतर प्रदर्शन करना।
Unbuffered Output Very Slow
स्रोत
2012-11-19 14:50:55
आपको Response.End() http://stevesmithblog.com/blog/use-httpapplication-completerequest-instead-of-response-end/ –
से बचने के लिए अपडेट किया जाना चाहिए CompleteRequest() का उपयोग करने के लिए। – womp
अनुपलब्ध दृश्य के बारे में त्रुटियों से बचने के लिए "वापसी सामग्री (" ")" द्वारा "वापसी दृश्य()" को प्रतिस्थापित करने के लिए उपयोगी हो सकता है। लेकिन क्या यह दृष्टिकोण सुरक्षित रूप से है? –