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

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

我有一个SPA和一个WebAPI。

用户单击SPA上的链接,该链接用于下载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
}

响应头是(注意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

原始请求标头(如果有兴趣的话)

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. 如何编写动作方法以返回两个不同类型的文件?
javascript c# single-page-application asp.net-core-webapi multipart
1个回答
0
投票

您无法在同一请求中返回2个不同的文件。您可以将内容嵌入包含2个内容的json对象中,但是随后您必须找出一种显示文件的方式,或者可以返回2个文件的URI,然后分别对文件进行2个请求。

我个人会选择后一种方法,因为这是最简单,最灵活的方法,具体取决于您打算对文件进行的处理。

希望有所帮助

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