如何 return 2 个文档(PDF 和 XFDF)从 C# .NET Core WebAPI 控制器到 SPA?

How to return 2 documents (PDF and XFDF) from a C# .NET Core WebAPI controller to a SPA?

我有一个 SPA 和一个 WebAPI。

用户在 SPA 上单击 link,这意味着下载 2 个文件(一个 PDF 和一个 XFDF)。


我有这个 WebAPI 操作(来源:What's the best way to serve up multiple binary files from a single WebApi method?

    [HttpGet]
    [Route("/api/files/both/{id}")]
    public HttpResponseMessage GetBothFiles([FromRoute][Required]string id)
    {
        StreamContent pdfContent =null;
        {
            var path = "location of PDF on server";
            var stream = new FileStream(path, FileMode.Open);
            pdfContent = new StreamContent(stream);
            pdfContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/vnd.adobe.xfdf");
        }

        StreamContent xfdfContent = null;
        {
            var path = "location of XFDF on server";
            var stream = new FileStream(path, FileMode.Open);
            xfdfContent = new StreamContent(stream);
            xfdfContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/pdf");
        }

        var content = new MultipartContent();
        content.Add(pdfContent);
        content.Add(xfdfContent);
        var response = new HttpResponseMessage();
        response.Content = content;
        return response;
    }

我在 SPA 中这样做

window.location.href = "/api/files/both/5";

结果。在浏览器中显示 JSON

{
    "Version": "1.1",
    "Content": [{
            "Headers": [{
                    "Key": "Content-Type",
                    "Value": ["application/vnd.adobe.xfdf"]
                }
            ]
        }, {
            "Headers": [{
                    "Key": "Content-Type",
                    "Value": ["application/pdf"]
                }
            ]
        }
    ],
    "StatusCode": 200,
    "ReasonPhrase": "OK",
    "Headers": [],
    "TrailingHeaders": [],
    "RequestMessage": null,
    "IsSuccessStatusCode": true
}

响应 header 是(注意 content-type = application/json)

HTTP/1.1 200 OK
x-powered-by: ASP.NET
content-length: 290
content-type: application/json; charset=utf-8
server: Microsoft-IIS/10.0
request-context: appId=cid-v1:e6b3643a-19a5-4605-a657-5e7333e7b99a
date: Tue, 04 Feb 2020 11:31:49 GMT
connection: close
Vary: Accept-Encoding

原始请求header(如果有兴趣)

Host: localhost:8101
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:8101/
DNT: 1
Connection: keep-alive
Cookie: MySession=....
Upgrade-Insecure-Requests: 1

问题

  1. 如何将动作方法编程为return 2 个不同类型的文件?

您不能在同一个请求中 return 2 个不同的文件。您可以将内容嵌入到包含 2 个内容的 json 对象中,但是您必须想出一种显示文件的方法,或者您可以 return 这两个文件的 URI,然后分别对文件发出 2 个请求。

就我个人而言,我会选择后一种选择,因为它是最简单和最灵活的,具体取决于您打算对文件执行的操作。

希望对您有所帮助

另一种选择是压缩 both/multiple 个文件并将其 return 作为单个文件。