我有一个应该返回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");
}当我检查whatisThis变量时,我看到内容类型和内容处置在我的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端的问题。
发布于 2017-04-05 21:25:03
我首先将这篇文章作为答案,因为它更容易格式化代码!
我创建了一个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;
}https://stackoverflow.com/questions/43210055
复制相似问题