从Web API返回的PDF无法打开。打开此文档时出错。文件已损坏,无法修复

问题描述 投票:-2回答:1

我有一个返回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不能。

打开此文档时出错。文件已损坏,无法修复。

enter image description here

c# asp.net-mvc pdf asp.net-web-api
1个回答
1
投票

基于@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;
}
© www.soinside.com 2019 - 2024. All rights reserved.