我在 Asp.NET 中编写了以下代码,我正在尝试将其转换为 MVC,但不确定如何在 Action 中执行此操作
HttpContext context;
context.Response.ContentType = "application/pdf";
context.Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", filename));
context.Response.WriteFile(filename);
context.Response.Flush();
context.Response.SuppressContent = true;
最佳答案
public ActionResult Download()
{
var cd = new ContentDisposition
{
Inline = false,
FileName = filename
};
Response.SuppressContent = true;
Response.AppendHeader("Content-Disposition", cd.ToString());
return this.File(filename, MediaTypeNames.Application.Pdf);
}
更新:
因此,您有一个生成 PDF 文件的服务器端脚本 (PDF.axd
)。您的文件系统上没有存储 pdf 文件。在这种情况下,您需要首先获取 pdf,然后将其流式传输到客户端:
public ActionResult Download()
{
byte[] pdfBuffer = null;
using (var client = new WebClient())
{
var url = string.Format("PDF.axd?file={0}.pdf", voucherDetail.Guid);
pdfBuffer = client.DownloadData(url);
}
var cd = new ContentDisposition
{
Inline = false,
FileName = "file.pdf"
};
Response.SuppressContent = true;
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(pdfBuffer, MediaTypeNames.Application.Pdf);
}
此 Controller 操作的实用性值得怀疑,因为您已经有一个可以完成这项工作的脚本。
关于asp.net-mvc - 如何让 MVC 返回 Context 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1896046/