【发布时间】:2020-05-20 05:38:03
【问题描述】:
我有一个 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
问题
- 如何编写action方法返回2个不同类型的文件?
【问题讨论】:
标签: javascript c# single-page-application asp.net-core-webapi multipart