首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从WebAPI传递pdf并从MVC控制器读取pdf?

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

Stack Overflow用户
提问于 2017-04-04 22:26:21
回答 1查看 12.4K关注 0票数 4

我有一个应该返回PDF的Web API服务。

然后,我尝试调用WebAPI方法来读取PDF。

下面是我的API方法:

代码语言:javascript
复制
    [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的内容。我不确定我在哪里做错了。

控制器方法:

代码语言:javascript
复制
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站点中的内容作为字符串读取,我会看到。(我看不到文件的实际内容)

代码语言:javascript
复制
{"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端的问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-05 21:25:03

我首先将这篇文章作为答案,因为它更容易格式化代码!

我创建了一个API端点来返回PDF文件,如果从浏览器调用它,文件就会按预期打开。

由于您的API似乎不能做到这一点,让我们假设问题就在那里,因此如下所示。

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

代码语言:javascript
复制
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;
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43210055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档