使用 ASP.NET Core 将 PDF 返回到浏览器 [英] Return PDF to the Browser using ASP.NET Core

查看:43
本文介绍了使用 ASP.NET Core 将 PDF 返回到浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ASP.Net 核心中创建了 Wep API 来返回 PDF.这是我的代码:

I created the Wep API in ASP.Net core to return the PDF. Here is my code:

public HttpResponseMessage Get(int id)
{
    var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);           
    var stream = new System.IO.FileStream(@"C:Usersshoba_eswarDocumentsREquest.pdf", System.IO.FileMode.Open);
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = "NewTab";
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
    return response;
}

但它只返回 JSON 响应:

But it returns only the JSON response:

{
   "version":{
      "major":1,
      "minor":1,
      "build":-1,
      "revision":-1,
      "majorRevision":-1,
      "minorRevision":-1
   },
   "content":{
      "headers":[
         {
            "key":"Content-Disposition",
            "value":[
               "attachment; filename=NewTab"
            ]
         },
         {
            "key":"Content-Type",
            "value":[
               "application/pdf"
            ]
         }
      ]
   },
   "statusCode":200,
   "reasonPhrase":"OK",
   "headers":[

   ],
   "requestMessage":null,
   "isSuccessStatusCode":true
}

我在这里做错了什么吗?

Am I doing anything wrong here?

推荐答案

ASP.NET Core HTTPRequestMessage 返回奇怪的 JSON 消息,ASP.NET Core 不支持返回 HttpResponseMessage(您安装了什么包来访问该类型?).

As explained in ASP.NET Core HTTPRequestMessage returns strange JSON message, ASP.NET Core does not support returning an HttpResponseMessage (what package did you install to get access to that type?).

因此,序列化程序只是将 HttpResponseMessage 的所有公共属性写入输出,就像处理任何其他不受支持的响应类型一样.

Because of this, the serializer is simply writing all public properties of the HttpResponseMessage to the output, as it would with any other unsupported response type.

要支持自定义响应,您必须返回一个 IActionResult 实现类型.有很多.在您的情况下,我会查看 FileStreamResult:

To support custom responses, you must return an IActionResult-implementing type. There's plenty of those. In your case, I'd look into the FileStreamResult:

public IActionResult Get(int id)
{
    var stream = new FileStream(@"path	ofile", FileMode.Open);
    return new FileStreamResult(stream, "application/pdf");     
}

或者简单地使用 PhysicalFileResult,为您处理流:

Or simply use a PhysicalFileResult, where the stream is handled for you:

public IActionResult Get(int id)
{
    return new PhysicalFileResult(@"path	ofile", "application/pdf");
}

当然所有这些都可以使用辅助方法来简化,例如 Controller.File():

Of course all of this can be simplified using helper methods, such as Controller.File():

public IActionResult Get(int id)
{
    var stream = new FileStream(@"path	ofile", FileMode.Open);
    return File(stream, "application/pdf", "FileDownloadName.ext");
}

这只是抽象了 FileContentResultFileStreamResult(对于这个重载,后者)的创建.

This simply abstracts the creation of a FileContentResult or FileStreamResult (for this overload, the latter).

或者,如果您要转换较旧的 MVC 或 Web API 应用程序并且不想一次转换所有代码,请添加对 WebApiCompatShim (NuGet) 并将您当前的代码包装在 ResponseMessageResult:

Or if you're converting an older MVC or Web API application and don't want to convert all your code at once, add a reference to WebApiCompatShim (NuGet) and wrap your current code in a ResponseMessageResult:

public IActionResult Get(int id)
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);           
    var stream = ...
    response.Content...

    return new ResponseMessageResult(response);
}

如果您不想使用 return File(fileName, contentType, fileDownloadName),则 FileStreamResult 不支持从构造函数或通过属性.

If you don't want to use return File(fileName, contentType, fileDownloadName), then the FileStreamResult doesn't support setting the content-disposition header from the constructor or through properties.

在这种情况下,您必须在返回文件结果之前自己将该响应标头添加到响应中:

In that case you'll have to add that response header to the response yourself before returning the file result:

var contentDisposition = new ContentDispositionHeaderValue("attachment");
contentDisposition.SetHttpFileName("foo.txt");
Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();

这篇关于使用 ASP.NET Core 将 PDF 返回到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆