Gra*_*ant 17 response httpexception asp.net-mvc-2
我有一个视图使用响应BinaryWrite方法呈现流.这在使用Beta 2的ASP.NET 4下工作正常,但在RC版本中引发了这个异常:
"HttpException","使用自定义TextWriter时,OutputStream不可用."
<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (ViewData["Error"] == null)
{
Response.Buffer = true;
Response.Clear();
Response.ContentType = ViewData["DocType"] as string;
Response.AddHeader("content-disposition", ViewData["Disposition"] as string);
Response.CacheControl = "No-cache";
MemoryStream stream = ViewData["DocAsStream"] as MemoryStream;
Response.BinaryWrite(stream.ToArray());
Response.Flush();
Response.Close();
}
}
</script>
</script>
Run Code Online (Sandbox Code Playgroud)
视图是从客户端重定向生成的(使用Url.Action帮助程序在前一页中使用jquery替换位置调用来渲染链接).这都在iframe中.
任何人都知道为什么会这样?
Lev*_*evi 17
当ViewPage开始执行时,它会假定有关请求的其余部分的某些事情.绊倒你的特殊事情是ViewPage假定请求的其余部分将是普通的HTML或其他一些文本响应,因此它将响应的TextWriter切换为自己的编写器.
在您的情况下,您应该创建一个新的ActionResult派生类,其ExecuteResult方法封装了Page_Load方法中的逻辑.您的action方法应返回自定义类的实例,并且调用者将在适当的时间运行ExecuteResult方法.这会完全绕过视图引擎,从而防止您运行的错误并为您带来轻微的性能提升.
Chr*_*ris 11
我做了Levi的回答.这实际上非常简单.我的代码将一个图像写入响应,该响应先前是在各种检查后从文件系统中获取的.
public class BookImageResult : ActionResult
{
private readonly GraphicReport graphicReport;
public BookImageResult(GraphicReport graphicReport)
{
this.graphicReport = graphicReport;
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.RequestContext.HttpContext.Response;
response.Clear();
response.ContentType = graphicReport.ContentType;
response.BinaryWrite(graphicReport.Image);
response.End();
}
}
Run Code Online (Sandbox Code Playgroud)
控制器末尾的行看起来像这样:
return new BookImageResult(graphicReport);
Run Code Online (Sandbox Code Playgroud)
有人将Levi的回答标记为答案!
| 归档时间: |
|
| 查看次数: |
14226 次 |
| 最近记录: |