By Joonas Püüa


2016-01-18 11:00:29 8 Comments

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;

    }

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

3 comments

@MoSad 2016-12-16 12:49:01

Try this!

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

@Ian Auty 2016-01-18 12:33:22

Does setting HttpContext.Response.ContentType = "application/pdf" help at all?

This should fit your needs:

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;                                
    }

@Joonas Püüa 2016-01-18 12:45:32

nope, it does not help. Result remains the same.

@Ian Auty 2016-01-18 13:03:56

Does "headers": [], have anything populated now? As I can see from your initial post that it's empty. What build of asp.net 5 are you using, and is it full .net or coreclr?

@Joonas Püüa 2016-01-18 13:20:57

Nope, it remains empty.

@Joonas Püüa 2016-01-18 13:21:41

Full - dnx451 ,build rc1-final

@Joonas Püüa 2016-01-18 13:31:47

If I add the header manually to HttpResponseMessage like that: result.Headers.Add("Content-Type", "application/pdf"); it throws : "Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."

@Joonas Püüa 2016-01-18 13:51:13

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.

Continues : Return file from ASP.NET 5 Web API

Thanks

Related Questions

Sponsored Content

6 Answered Questions

[SOLVED] How to secure an ASP.NET Web API

9 Answered Questions

1 Answered Questions

7 Answered Questions

[SOLVED] Returning binary file from controller in ASP.NET Web API

5 Answered Questions

[SOLVED] ServiceStack vs ASP.Net Web API

15 Answered Questions

[SOLVED] Pass an array of integers to ASP.NET Web API?

29 Answered Questions

[SOLVED] How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

11 Answered Questions

[SOLVED] Best practice to return errors in ASP.NET Web API

11 Answered Questions

[SOLVED] WCF vs ASP.NET Web API

12 Answered Questions

[SOLVED] Accessing Session Using ASP.NET Web API

Sponsored Content