1

Built basic API controller that downloads a PDF file that is stored locally within the project.

Is there a way to modify the code so that the PDF can be downloaded from a URL link? I've tried the different methods that are available to use in the HostingEnvironment Class.

Here is an example:

DownloadController.cs

using System.IO;
using System.Net.Http;
using System.Web.Hosting;
using System.Web.Http;

namespace DownloadAPITest.Controllers
{
    public class DownloadController : ApiController
    {
        public HttpResponseMessage Get()
        {
            HttpResponseMessage result = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            //string pdfLocation = HostingEnvironment.MapPath("~/Content/SE_SurfaceWater_Tbl.pdf");
            //string pdfLocation = HostingEnvironment.MapPath("http://***.***.local/ReportServer?/proj_20800014/SE_SurfaceWater_Tbl&rs:Command=Render&rs:Format=PDF");

            string pdfLocation = HostingEnvironment.
         
            var stream = new MemoryStream(System.IO.File.ReadAllBytes(pdfLocation));
            stream.Position = 0;

            if (stream == null)
                return Request.CreateResponse(System.Net.HttpStatusCode.NotFound);

            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline"); //"inline" to make it appear on the browser //"attachment" for direct download
            result.Content.Headers.ContentDisposition.FileName = "fileTest.pdf";
            result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
            result.Content.Headers.ContentLength = stream.Length;

            return result;
        }
    }
}
minTwin
  • 1,181
  • 2
  • 21
  • 35
  • This might help: https://stackoverflow.com/questions/307688/how-to-download-a-file-from-a-url-in-c – VDWWD Jan 07 '22 at 22:31

0 Answers0