asp.net-mvc - 如何让 MVC 返回 Context 类型

标签 asp.net-mvc pdf-generation

我在 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/

相关文章:

linux - 将字体嵌入到 PDF 表单中

excel - 将多张纸保存为 .pdf

javascript - 使用 Internet Explorer 10 及以下版本保存 Base64 编码的 PDF

django - 比萨pdf转换器在使用大表时非常慢

java - iText - 如果特定行位于页面底部,则在下一页上设置特定行

c# - 找不到存储过程 'dbo.aspnet_UsersInRoles_GetRolesForUser'

c# - 在 MVC 中存储/调用重复代码块

c# - ASP.NET、MVC、C# 应用程序 - 为不同的 View 修改 _Layout.cshtml

javascript - 将 "Id"选定的复选框传递给模态 Bootstrap 并发送到 Controller

asp.net-mvc - AntiForgeryToken 重用