使用Asp.net核心将PDF返回到浏览器

前端之家收集整理的这篇文章主要介绍了使用Asp.net核心将PDF返回到浏览器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在ASP.Net核心中创建了Wep API以返回PDF.这是我的代码
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响应:

{
   "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
}

我在这做错了吗?

解决方法

ASP.NET Core HTTPRequestMessage returns strange JSON message中所述,ASP.NET Core不支持返回HttpResponseMessage(您安装了哪些软件包以访问该类型?).

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

支持自定义响应,您必须返回IActionResult实现类型.有plenty of those.在你的情况下,我会调查FileStreamResult

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

或者只需使用PhysicalFileResult,即可为您处理流:

public IActionResult Get(int id)
{
    return new FileStreamResult(@"path\to\file","application/pdf");
}

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

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

这简单地抽象了FileContentResult或FileStreamResult的创建(对于这个重载,后者).

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

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

    return new ResponseMessageResult(response);
}

如果您不想使用返回文件(fileName,contentType,fileDownloadName),则FileStreamResult不支持从构造函数或通过属性设置content-disposition标头.

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

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

猜你在找的asp.Net相关文章