c# - 如何从 Web API 传递 pdf 并从 MVC Controller 读取 pdf?

标签 c# asp.net-mvc asp.net-web-api

我有一个应该返回 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 内容。我不确定我哪里出错了。

Controller 方法:
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 端的问题。

最佳答案

我最初会将此作为答案发布,因为格式化代码更容易!
我创建了一个 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;
}

关于c# - 如何从 Web API 传递 pdf 并从 MVC Controller 读取 pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43210055/

相关文章:

c# - 获取音频设备列表并使用 C# 选择一个

c# - 将 Web API 用于 Windows 服务以通过轮询接收命令和执行任务?

c# - 从代码和网站调用Web API

c# - 在 MVC 中使用 EF 创建多个数据库并将数据库名称作为 web.config 中的变量传递给 InitialCatalogue

c# - 实例化扩展方法? C#

c# - 无法确定类型 "Class"的 JSON 对象类型

c# - 等待后任务继续不工作

c# - 具有重载的 ASP.NET MVC Web API 属性路由

asp.net - 我应该在哪里保存由 ASP.NET Web API 动态生成的文件?

c# - 加密 JWT token