5

I have written a controller to download/stream file to the clients local machine. The code doesn't stream the file on doing a GET to the url besides only produces response body.

What is the problem with streamcontent method. On debug i could not find the issue.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Text;

namespace FileDownloaderService.Controllers
{
    [Route("api/[controller]")]
    public class FileDownloadController : Controller
    {

        [HttpGet]
        public HttpResponseMessage Get() {
            string filename = "ASPNETCore" + ".pdf";
            string path = @"C:\Users\INPYADAV\Documents\LearningMaterial\"+ filename;

            if (System.IO.File.Exists(path)) {
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                var stream = new FileStream(path, FileMode.Open);
                stream.Position = 0;
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = filename };
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
                result.Content.Headers.ContentDisposition.FileName = filename;
                return result;
            }
            else
            {
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.Gone);
                return result;
            }
        }
        }
    }

Response:

{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=ASPNETCore.pdf"]},{"key":"Content-Type","value":["application/pdf"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}
  • [Write PDF stream to response stream](https://stackoverflow.com/questions/5828315/write-pdf-stream-to-response-stream) might be helpful for this. – Poosh Jun 20 '17 at 04:12
  • Is there any way i could use the HttpResponseMessage to stream the file to the local disk? –  Jun 20 '17 at 04:48

1 Answers1

7

In ASP.NET Core, you need to be using an IActionResult if you are sending a custom response. All other responses will be serialized (JSON by default) and sent as response body.

Refer to the answer at File Streaming in ASP.NET Core

Pradeep Kumar
  • 1,281
  • 7
  • 9