如何在JSON响应中正确返回PDF?

问题描述 投票:0回答:1

我需要在我的WebApi 2 响应中返回两个PDF文件,实际上我是通过将pdf文件作为Base64 string发送来完成此操作的,但我的问题是如果方法正确或有更好的方法可以这样做] ..

这是我的构造函数,我的Api返回:

public class DCW
{
    public string numdoc { get; set; }
    public string pdf { get; set; }
    public string pdf_regalo { get; set; }

    public string Base64(string path)
    {
        // Method to convert pdf to Base64
        byte[] bytes = File.ReadAllBytes(path);
        string file = Convert.ToBase64String(bytes);

        return file;
    }
}

这是我的controller的样子:

  [Route("api/[controller]")]
    public class DriverController : Controller
    {
        [HttpPost]
        public DCW Post([FromBody]Scontrino scontrino)
        {

            DCW dcw = new DCW();
            string pdf = dcw.Base64("C:/users/imytyuk/Desktop/TEST/XXX01_731378.pdf");
            string pdf_regalo = dcw.Base64("C:/users/imytyuk/Desktop/TEST/XXX01_731378_regalo.pdf");

            dcw.numdoc = "5454835";
            dcw.pdf = pdf;
            dcw.pdf_regalo = pdf_regalo;

            return dcw;


        }

    }

实际上是以下答复:

{
    "numdoc": "5454835",
    "pdf": "XAGCTiT45cuco3YWQ6Ckz9e1//f0nr1NYb8f9crD26pyfKa4QBrqOsjf0d8vsaJmn1if6BbiRtHkKZW5kc3RyZWFtCmVuZG2QJ4G83q5nqMbS1sNHnZsr7uBPMd8Bkdbr4AplbmRzdHJlYW0KZW5kb2JqCjE5IDAgb2JqCjc3MAplbmRvYmoKMjAgMCBvYmoKPDwvRmlsdGVyL0ZsYXRlRGVjb2RlL1R5cGUvWFJlZi9XWzEgMADSDSAeM2RTM0MzBCOTZCRTA0QUM4OTNFREJFNT5dL0RlY29kZVBhcm1zPDwvQ29sdW1ucyA1L1ByZWRpY3RvciAxMj4+L0xlbmd0aCA5NCAgICAgICAgPj4Kc3RyZWFtCnicNcuxDYAwDETR8wVFoUdiCCqGYhMGYAyo2IAx2CVEwdgImqfTl00AqiSStLSN/Bo+NZxe6ghQkE1Ng4lyeKn9d6nUZsNNcPV+7Yh/jxMK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Ci9DcmVhdGlvbkRhdGUgKEQ6MjAyMDA0MDcxMTM0NTQrMDInMDAnKQovUHJvZHVjZXIgKFBERmxpYiBQZXJzb25hbGl6YXRpb24gU2VydmVyIDkuMC40IFwoSkRLIDEuNi9MaW51eC14ODZfNjRcKSkKPj4KZW5kb2JqCjEyIDAgb2J="
}

我需要在WebApi 2响应中返回两个PDF文件,实际上我是通过简单地将pdf文件作为Base64字符串发送来实现的,但是我的问题是方法是否正确或是否存在...

c# json api asp.net-web-api2
1个回答
1
投票

简短的答案是没有。这是传输文件的合法方法,但是有几个缺点:

© www.soinside.com 2019 - 2024. All rights reserved.