【发布时间】:2015-12-30 15:32:17
【问题描述】:
我正在使用 WebAPI 下载 .pdf 文件,如下所示:
[HttpGet]
public async Task<HttpResponseMessage> DownloadFile(string id, bool attachment = true)
{
HttpResponseMessage result = null;
try
{
MyService service = new MyService();
var bytes = await service.DownloadFileAsync(id);
if (bytes != null)
{
result = GetBinaryFile(personalDocument, string.Format("{0}.pdf", id), attachment);
}
else
{
result = new HttpResponseMessage(HttpStatusCode.NotFound);
}
}
catch (Exception ex)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "ServerError" });
}
return result;
}
private HttpResponseMessage GetBinaryFile(byte[] bytes, string fileName, bool attachment)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
// result.Content = new ByteArrayContent(bytes);
result.Content = new StreamContent(new System.IO.MemoryStream(bytes));
//result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
if (attachment)
{
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
}
result.Content.Headers.ContentDisposition.FileName = fileName;
result.Content.Headers.ContentLength = bytes.Length;
return result;
}
现在,我看到它冻结了我的网站,所以我想更改它,并通过处理程序下载一个 pdf 文件,是否可以通过客户端的任何更改路由到 IHttpHandler?按 Route 属性?
【问题讨论】:
-
也可以使 GetBinaryFile() 方法异步
-
GetBinaryFile 只是用 HttpResponseMessage 包装文件并返回结果。
-
getbinaryfile 会冻结您的网站。你需要能够调用等待
-
我把它作为异步方法,问题仍然存在..
-
它是否挂在所有浏览器上?当我意识到 PDF 在除 IE11 之外的所有其他浏览器上都可以正常下载时,我目前正试图找出一个类似的问题
标签: c# asp.net-web-api asp.net-web-api2