asp.net-web-api – 如何从ASP.net 5 web api返回文件

在asp.net 5中创建了wep api.我想回复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;

    }

如何将实际文件作为响应而不是JSON返回?我使用Postman作为测试客户端.

解决方法

使用IActionResult而不是HttpResponseMessage.并返回FileStreamResult,并使其工作.

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

继续:Return file from ASP.NET 5 Web API

谢谢

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....