如何从ASP.net 5的Web API返回的文件 [英] How to return file from ASP.net 5 web api

查看:600
本文介绍了如何从ASP.net 5的Web API返回的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在asp.net 5.我特林返回后请求文件响应创建的WEP API。但是,而不是文件的响应看起来像
`

Created wep api in asp.net 5. I am tring to return file response for Post request. But instead of file the response looks like `

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

code:

    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?我用的邮差作为测试客户端。

How can I return the real file as the response instead of JSON ?I am using Postman as test client.

推荐答案

代替了Htt presponseMessage IActionResult。并返回FileStreamResult,并得到了它的工作。

used IActionResult instead of HttpResponseMessage. And returned FileStreamResult, and got it working.

有一个新的问题,该文件是不是我从服务器流打开。但是,将创建一个新的问题。

Got a new problem, the file is not the one I open with the stream from server. But will create a new question for that.

继续: Asp.net 5的Web API返回的文件响应

感谢

这篇关于如何从ASP.net 5的Web API返回的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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