【问题标题】:How do I get MVC to return a Context type如何让 MVC 返回 Context 类型
【发布时间】:2010-12-26 03:30:42
【问题描述】:

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

【问题讨论】:

    标签: asp.net-mvc pdf-generation


    【解决方案1】:
    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); 
    }
    

    这个控制器动作的有用性值得怀疑,因为您已经有一个脚本来完成这项工作。

    【讨论】:

    • 这看起来正确,但我得到“不是有效的虚拟路径”。即使文件和 URL 正确
    • 你在哪一行得到这个异常? filename 是绝对路径吗?
    • 这是生成文件名的行。字符串文件名 = (string.Format("PDF.axd?file={0}.pdf",voucherDetail.Guid));我也尝试过使用带有 HTML:\\ 的完整 URL 但得到相同的响应
    • 将文件名放在 IE 的 URL 中可以正常工作并显示 PDF
    • 您混淆了a filenameurl address。请查看我的更新。
    【解决方案2】:

    您的意思是“内容”而不是“上下文”类型,是吗?

    也许这篇 SO 帖子会有所帮助: ASP.NET MVC and text/xml content type

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 2014-01-13
      • 1970-01-01
      相关资源
      最近更新 更多