【问题标题】:ASP.NET MVC with custom actionresult: outputStream is not available when a custom TextWriter is used具有自定义操作结果的 ASP.NET MVC:使用自定义 TextWriter 时 outputStream 不可用
【发布时间】:2014-06-24 06:04:26
【问题描述】:

我想生成一个 PDF,我在我的控制器中使用以下代码来调用它:

public PdfActionResult Index()
{
   return new PdfActionResult("");
}

自定义操作结果“pdfActionResult”如下所示:

 public override void ExecuteResult(ControllerContext context)
        {
            var _pdfConverter = new PdfConverter { MediaType = "Print" };
            var response = context.HttpContext.Response;
            response.Clear();
            response.AddHeader("Content-Type", "application/pdf");
            response.AddHeader("Content-Disposition", String.Format("{0}; filename={1}.pdf;", true ? "attachment" : "inline", "bla"));
            var z = context.HttpContext.Request.Url.AbsoluteUri;
            z = z.Substring(0, z.IndexOf("?", System.StringComparison.Ordinal));
            var b = _pdfConverter.GetPdfBytesFromUrl(z);
            response.OutputStream.Write(b,0,b.Length);
            response.Close();
            response.Flush();
            response.End();
        }

我收到以下异常:

System.Web.HttpException: OutputStream is not available when a custom TextWriter is used.

我已阅读其他建议使用自定义操作结果的 SO 帖子,所以我这样做了,但没有成功。

怎么了?

【问题讨论】:

  • 尝试使用 Response.BinaryWrite
  • @dotnetstep 我试过了,同样的错误。
  • 代替 context.HttpContext.Response 试试 HttpContext.Current.Response。
  • @dotnetstep 也不起作用:(即使与 BinaryWrite() 结合使用。

标签: c# asp.net-mvc actionresult


【解决方案1】:

在这种情况下,我认为没有任何理由创建自定义 ActionResult。返回 PDF 数据是一项非常常见的任务,最明智的做法是使用内置的FileResult

此外,您的PdfActionResult 在这里混合了两个问题,(1) PDF 数据的创建和 (2) 将其附加到响应中。 ActionResult 的主要关注点是如何将 Action 生成的资源交付给客户端,不自己生成资源

试试这个:

public FileResult Index()
{
    var _pdfConverter = new PdfConverter { MediaType = "Print" };
    var url = Request.Url.AbsolutePath;
    var pdfBytes = _pdfConverter.GetPdfBytesFromUrl(url);

    return File(pdfBytes, "application/pdf", "bla.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
    相关资源
    最近更新 更多