如何从 ASP.net 5 网站 return 文件 api

How to return file from ASP.net 5 web api

在 asp.net 中创建了 wep api 5. 我正在尝试 return 文件对 Post 请求的响应。但是不是文件,而是响应看起来像 `

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

代码:

    public HttpResponseMessage Post([FromBody]DocumentViewModel vm)
    {
        try
        {
            if (ModelState.IsValid)
            {

                var Document = _repository.GetDocumentByGuid(vm.DocumentGuid, User.Identity.Name);
                var Params = Helper.ClientInputToRealValues(vm.Parameters, Document.DataFields);
                var file = Helper.GeneratePdf(Helper.InsertValues(Params, Document.Content));                 

                var result = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(System.IO.File.ReadAllBytes(file))
                };
                result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = "test.pdf"
                };
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                return result;

            }

        }
        catch (Exception ex)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return null;
        }
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return null;

    }

如何 return 将真实文件作为响应而不是 JSON?我正在使用 Postman 作为测试客户端。

设置 HttpContext.Response.ContentType = "application/pdf" 有帮助吗?

这应该符合您的需要:

public FileResult TestDownload()
    {
        HttpContext.Response.ContentType = "application/pdf";
        FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes("YOUR PATH TO PDF"), "application/pdf")
        {
            FileDownloadName = "test.pdf"
        };

        return result;                                
    }

使用 IActionResult 而不是 HttpResponseMessage。并返回 FileStreamResult,并使其正常工作。

遇到新问题,文件不是我用服务器流打开的文件。但会为此创造一个新问题。

继续:

谢谢

这是 "low-level" HTTP 方法,它应该适用于 ASP.NET WebAPI 或 ASP.NET MVC。

[HttpGet]
public HttpResponseMessage Download()
{
  var fs = new FileStream(myfileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, 32768, true);
  var response = new HttpResponseMessage {
    Content = new StreamContent(fs);
  }
  response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
  response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  return response;
}