如何从WebAPI传递pdf并从MVC控制器读取pdf?

我有一个应该返回PDF的Web API服务。
然后我试图调用该WebAPI方法来读取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"); } 

当我检查whatis这个变量时,我看到内容类型和从我的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端点来返回一个PDF文件,如果我从浏览器调用它,该文件将按预期打开。
由于您的API似乎没有这样做,我们假设存在问题,因此这样做。

这是端点代码,与您的端点代码非常相似,但缺少ContentDisposition内容:

 public HttpResponseMessage Get() { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); FileStream fileStream = File.OpenRead("FileName.pdf"); response.Content = new StreamContent(fileStream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); return response; }