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

查看:810
本文介绍了使用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:\Users\shoba_eswar\Documents\REquest.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?

推荐答案

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实现类型.有很多这样的.对于您的情况,我将查看

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\to\file", 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\to\file", "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\to\file", 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应用程序,并且不想一次转换所有代码,请添加对 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不支持从构造函数或通过属性设置content-disposition标头.

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天全站免登陆