使用自定义TextWriter时,OutputStream不可用

这是我的函数,它将pdf转换为png图像,它在这一行上抛出一个错误 – > stream.WriteTo(Response.OutputStream); 有什么不对??

protected void CreatePngFromPdf() { try { string PDFLocation = string.Format(@"\\XXXX\{0}\{1}\{2}.pdf", Yr, Loc.Substring(0, 4), Loc.Substring(4, 4)); Utilities.WebPDF.PDF WebPDF = new DocuvaultMVC.Utilities.WebPDF.PDF(); WebPDF.Credentials = new NetworkCredential(@"xyz", "xyz"); byte[] png = WebPDF.StreamPdfPageAsPngResize(PDFLocation,PageNumber, 612, 792); MemoryStream ms = new MemoryStream(png); MemoryStream stream = new MemoryStream(); int newWidth = 612; int newHeight = 792; System.Drawing.Image newImg = System.Drawing.Image.FromStream(ms); Bitmap temp = new Bitmap(newWidth, newHeight, newImg.PixelFormat); Graphics newImage = Graphics.FromImage(temp); newImage.DrawImage(newImg, 0, 0, newWidth, newHeight); newImg.Dispose(); temp.Save(stream, ImageFormat.Png); stream.WriteTo(Response.OutputStream); temp.Dispose(); stream.Dispose(); } catch (Exception ex) { Response.Write(ex.Message.ToString()); } } 

这与你的问题没有直接关系,但在做其他事情时我得到了同样的例外,所以我想我会把这个答案放在后面……

我只是在主页渲染时才获得此exception,而不是在进入相关控制器操作时。

在我意识到我已经使用了Html.Action (运行动作并发出HTML内联)而不是Url.Action (生成URL)时,会发生很多Url.Action

在我的情况下,原因是Controller.File方法中的错误参数。

第三个参数为null的 Controller.File方法将在浏览器窗口中呈现图像:

 public ActionResult GenerateImage(...) { ... return File(fileResult.Buffer, fileResult.ContentType, null); } 

带有第三个参数作为文件名的 Controller.File方法将触发在浏览器中下载图像:

 public ActionResult GenerateImage(...) { ... return File(fileResult.Buffer, fileResult.ContentType, "image.jpg"); } 

使用第三个参数作为扩展名的 Controller.File方法将导致错误: 使用自定义TextWriter时,OutputStream不可用

 public ActionResult GenerateImage(...) { ... return File(fileResult.Buffer, fileResult.ContentType, ".jpg"); }