我有一个返回PDF的web api控制器。 Abobe Reader XI 11.0.12没有打开一些PDF
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.BinaryWrite(myByteArray);
HttpContext.Current.Response.End();
上面的代码没有错误,PDF也可以在Adobe Reader中打开,也可以在所有流行的浏览器中打开。
但它确实抛出“服务器无法在发送HTTP标头后设置状态”。我一直在忽略,但想解决,所以我实现了下面的代码。
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.BinaryWrite(myByteArray);
HttpContext.Current.Response.Flush();
此代码也可以正常运行,但无法在Adobe Reader XI 11.0.12版中打开从此代码返回的PDF。 FF,Chrome,Edge可以显示PDF。 IE 11不能。
打开此文档时出错。文件已损坏,无法修复。
基于@mason响应和链接Returning binary file from controller in ASP.NET Web API我用以下代码替换了所有HttpContext.Current.Response
来解决此问题:
public HttpResponseMessage LoadPdf(int id)
{
//get PDF in myByteArray
//return PDF bytes as HttpResponseMessage
HttpResponseMessage result = new HttpResponseMessage();
Stream stream = new MemoryStream(myByteArray);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "my-doc.pdf" };
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.StatusCode = HttpStatusCode.OK;
return result;
}