FileContentResult可以使用,但将其下载为字节数组不起作用。

3

我正在尝试将HTML转换为PDF文件。

我有以下控制器:

    public ActionResult Offer([FromBody] DocumentTemplateInvoiceViewModel vm)
    {
        return this.Pdf(nameof(Offer), vm, "test.pdf");
    }

当我在这里进行POST请求时,我会收到文件并且可以打开它。真是美好的一天!
然而,如果我尝试做以下操作:
    var termsClient = new RestClient(ConfigurationManager.AppSettings["HostingUrl"]);
    var termsRequest = new RestRequest("/Document/Offer", Method.POST);
    termsRequest.AddJsonBody(vm);
    var json = JsonConvert.SerializeObject(vm);
    var termsBytes = termsClient.DownloadData(termsRequest);
    File.WriteAllBytes("LOCALPATH",termsBytes );

文件已损坏,我无法打开PDF。它有一定的大小,因此存储了一些字节。可能只是没有正确存储:D
我做错了什么?为什么从我的控制器获取的FileContentResult可以工作,但是下载数据时却损坏了?

检查原始请求。很有可能这两个请求正在请求两种不同的内容类型。 - Nkosi
2
由于问题的解决方式不太可能对未来的任何人有所帮助,我已经退还了你的悬赏并将其关闭为“无法重现”。如果您认为这里没有任何对他人有用的东西,请随意删除。(您应该能够自己删除它。您可能需要取消接受您自己的答案。我不记得系统允许什么。) - Cody Gray
2个回答

2
你把问题标记为MVC,所以我会尝试以MVC应用程序的方式回答。
REST对象似乎表明是WEB.API,但也许我错了。:)
如果你在谈论FileContentResult,那么我建议加入ContentType。
var contentType = System.Net.Mime.MediaTypeNames.Application.Pdf;

然后像这样加载FileContentResult:
var fcr = new FileContentResult(ms.ToArray(), contentType); //NOTE: Using a File Stream Result will not work.
fcr.FileDownloadName = FileName; 

我看到你正在使用PDF生成,这里是我用来生成PDF的FileContentResult的示例:

    public FileContentResult CreatePdfFileContentResult()
    {
        var contentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
        using (MemoryStream ms = new MemoryStream())
        {
            // Create an instance of the document class which represents the PDF document itself.
            Document document = new Document(PageSize.A4, 25, 25, 30, 30);
            // Create an instance to the PDF file by creating an instance of the PDF 
            // Writer class using the document and the filestrem in the constructor.
            PdfWriter writer = PdfWriter.GetInstance(document, ms);

            if (OnPdfMetaInformationAdd != null)
                OnPdfMetaInformationAdd(document, DataSource);

            // Open the document to enable you to write to the document
            document.Open();

            if (OnPdfContentAdd != null)
                OnPdfContentAdd(document, DataSource);
            else throw new NotImplementedException("OnPdfContentAdd event not defined");

            // Close the document
            document.Close();
            // Close the writer instance
            writer.Close();

            var fcr = new FileContentResult(ms.ToArray(), contentType); //NOTE: Using a File Stream Result will not work.
            fcr.FileDownloadName = FileName;                
            return fcr;
        }
    }

0

事实证明我是个白痴,问题完全不同。终端点只是返回了一个404错误,这个错误被下载并包装成一个文件(显然导致PDF文件损坏)。

所以这段代码完美地工作了。在Fiddler中查看请求很快就显示了问题所在。


是的,那可能发生。 :) 因此建议检查原始请求。活到老学到老。我也曾经历过这种情况。 - Nkosi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接