asp.net-mvc – 从Action写入输出流
发布时间:2020-05-23 15:41:26 所属栏目:asp.Net 来源:互联网
导读:由于某些奇怪的原因,我想将HTML直接写入控制器动作的响应流。 (我明白MVC的分离,但这是一个特例) 我可以直接写入HttpResponse流吗?在那种情况下,控制器动作应该返回哪个IView对象?我可以返回’null’吗? 我使用从FileResult派生的类来实现这个使用正常
|
由于某些奇怪的原因,我想将HTML直接写入控制器动作的响应流。
我可以直接写入HttpResponse流吗?在那种情况下,控制器动作应该返回哪个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);
}
}
控制器方法现在是这样的: 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 – ASP.NET MVC Validation将类添加到包含div
- asp.net – 什么时候调用Application_End,我该如何手动导致
- asp.net下经典数据库记录分页代码
- asp.net – 通过使用JQuery调用Web服务可能存在哪些威胁,如
- asp.net-mvc – DataAnnotation验证和自定义ModelBinder
- asp.net – 如何摆脱包含GridView的空div
- ASP MVC C#:是否可以将动态值传递给属性?
- 我的ASP.NET Web应用程序无法“找到”App_Code文件夹中的任
- asp.net – 使用回发解析.Net页面
- asp.net – CORS错误 – 请求的资源上没有“Access-Control
推荐文章
站长推荐
- asp.net-mvc-3 – 与ASP.NET MVC 3中的视图页面不
- asp.net-mvc – 在web.config文件中创建自定义变
- asp.net – 从DropDownList中删除列表项
- asp.net – 成员资格生成密码仅字母数字密码?
- asp.net汉字转拼音和获取汉字首字母的代码
- asp.net-mvc – ELMAH和SQL Server 2008 R2?
- asp.net – 避免使用CORS进行预检OPTIONS请求
- asp.net-core – 如何在.Net Core应用程序中读取
- asp.net-mvc – 忽略viewstart在asp.net mvc raz
- .net – 如何将变量传递给SqlDataSource的Select
热点阅读
