我有一個應該返回PDF的Web API服務。
然後我試圖調用該WebAPI方法來閱讀PDF。如何從WebAPI傳遞PDF並從MVC控制器讀取PDF?
這裏是我的API方法:
[HttpPost]
[Route("GetTestPDF")]
public HttpResponseMessage TestPDF()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(@"C:\MyPath\MyFile.pdf", FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "MyFile.pdf";
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
return Request.CreateResponse(HttpStatusCode.OK, response);
}
但是當我去讀取響應我沒有看到PDF格式的內容。我不確定我在哪裏出錯。
控制器的方法:
public ActionResult GetPDF()
{
var response = new HttpResponseMessage();
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(@"my local host");
response = httpClient.PostAsync(@"api/job/GetTestPDF", new StringContent(string.Empty)).Result;
}
var whatisThis = response.Content.ReadAsStringAsync().Result;
return new FileContentResult(Convert.FromBase64String(response.Content.ReadAsStringAsync().Result), "application/pdf");
}
當我審視whatisThis可變我看到的內容類型和內容dispostion正確地從我的API集。但是我沒有看到PDF的內容。
如何閱讀PDF內容?
編輯:
如果我讀的內容,在我的MVC的網站我看到的字符串。 (我沒有看到文件的實際內容)
{"Version":{"_Major":1,"_Minor":1,"_Build":-1,"_Revision":-1},"Content":{"Headers":[{"Key":"Content-Disposition","Value":["attachment; filename=MyFile.pdf"]},{"Key":"Content-Type","Value":["application/pdf"]}]},"StatusCode":200,"ReasonPhrase":"OK","Headers":[],"RequestMessage":null,"IsSuccessStatusCode":true}
我走過的WebAPI階梯,它是成功的閱讀和設置與文件內容的response.Content。
仍然不確定這是WebAPI端還是MVC端的問題。
如果您的API方法HTTPGET並從瀏覽器中調用它的PDF打開或下載如預期,並以PDF格式工作? –
FileContentResult的構造函數似乎需要一個字節數組,並且您可以閱讀響應內容,因此可能不會像讀取字符串那樣讀取數據:'返回新的FileContentResult(response.Content.ReadAsByteArrayAsync()。Result,「應用程序/ pdf「);' –
嗯。除了文檔的實際內容外,我可以看到所有內容。我沒有提出建議更改,並得到一個錯誤文檔不以%pdf – PrivateJoker