【问题标题】:BinaryWrite exception "OutputStream is not available when a custom TextWriter is used" in MVC 2 ASP.NET 4MVC 2 ASP.NET 4 中的 BinaryWrite 异常“使用自定义 TextWriter 时,OutputStream 不可用”
【发布时间】:2010-02-14 13:32:39
【问题描述】:

我有一个使用响应 BinaryWrite 方法呈现流的视图。这一切在 ASP.NET 4 下使用 Beta 2 运行良好,但在 RC 版本中抛出此异常:

"HttpException" , "OutputStream 不是 自定义 TextWriter 时可用 用过的。”

<%@ 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>

视图是从客户端重定向生成的(jquery 替换上一页中的位置调用当然使用 Url.Action 帮助器来呈现链接)。这一切都在 iframe 中。

有人知道为什么会这样吗?

【问题讨论】:

    标签: asp.net-mvc-2 response httpexception


    【解决方案1】:

    当一个 ViewPage 开始执行时,它会假设请求的其余部分的某些事情。让您感到困惑的是 ViewPage 假定请求的其余部分将是普通的 HTML 或其他文本响应,因此它将响应的 TextWriter 切换为自己的编写器。

    在您的情况下,您应该创建一个新的 ActionResult 派生类,其 ExecuteResult 方法将逻辑封装在您的 Page_Load 方法中。您的操作方法应返回您的自定义类的实例,调用程序将在适当的时间运行 ExecuteResult 方法。这会完全绕过视图引擎,从而防止您遇到错误并略微提升性能。

    【讨论】:

      【解决方案2】:

      我做了李维斯的回答。这实际上非常容易。我的代码将图像写入响应中,该图像是经过各种检查后从文件系统中获取的。

      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();
          }
      }
      

      控制器末尾的行看起来像这样:

      return new BookImageResult(graphicReport);
      

      有人将李维斯的回答标记为答案!

      【讨论】:

      • 网络表单呢?我正在尝试使用reportviewer。在页面加载方法中。
      【解决方案3】:

      做类似事情的另一种方法是使用内置的FileActionResult

      var bytes = GetPdfBytes("Performance Report", htmlString);
      return File(bytes, "binary/octet-stream", "Performance Report.pdf");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多