Asp.net-Mvc
HttpResponseMessage 內容不會顯示 PDF
我創建了一個 Web Api,它返回一個 HttpResponseMessage,其中內容設置為 PDF 文件。如果我直接呼叫 Web Api,它會很好地工作,並且 PDF 會在瀏覽器中呈現。
response.Content = new StreamContent(new FileStream(pdfLocation, FileMode.Open, FileAccess.Read)); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); response.Headers.ConnectionClose = true; return response;我有一個 MVC 客戶端想要聯繫 Web Api,請求 Pdf 文件,然後以與上述相同的方式將其呈現給使用者。
不幸的是,我不確定問題出在哪裡,但即使我設置了內容類型:
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");當我點擊呼叫 web api 的連結時,我得到了 HttpResponseMessage 的文本呈現。
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Connection: close Content-Disposition: attachment Content-Type: application/pdf }我認為客戶端應用程序缺少一些設置,允許它像我的 Web Api 一樣呈現 PDF ……
任何幫助,將不勝感激。謝謝
經過數小時的Google搜尋以及反複試驗,我在這裡解決了這個問題。
我沒有將響應的內容設置為 StreamContent,而是在 Web Api 端將其更改為 ByteArrayContent。
byte[] fileBytes = System.IO.File.ReadAllBytes(pdfLocation); response.Content = new ByteArrayContent(fileBytes); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = fileName; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");通過這種方式,我的 MVC 4 應用程序能夠使用 WebClient 和 DownloadData 方法下載 PDF。
internal byte[] DownloadFile(string requestUrl) { string serverUrl = _baseAddress + requestUrl; var client = new System.Net.WebClient(); client.Headers.Add("Content-Type", "application/pdf"); return client.DownloadData(serverUrl); }字節
$$ $$返回的數組可以很容易地轉換為 MemoryStream 在返回文件進行輸出之前…
Response.AddHeader("Content-Disposition", "inline; filename="+fileName); MemoryStream outputStream = new MemoryStream(); outputStream.Write(file, 0, file.Length); outputStream.Position = 0; return File(outputStream, "application/pdf");我希望這對其他人有用,因為我浪費了很多時間來讓它工作。