How to Return Files From Web API


  • Basic C# coding knowledge
  • Minimum knowledge of Web API
  • Understanding for the REST service

When we are working with REST service, it is very important to understand how to send files. In this article, we are going to discuss how to return files (PDF/Word/Excel) from Web API service.

I am going to explain a step by step process to transfer a file over Http REST service.

Let’s assume, we have a requirement to send a file based on the file type provided to the service request. For example, when we send the file type as PDF, service will return PDF file if we send Doc, service will return Word document. (I have taken this sample to cover all types of files).

We cannot send the file from its original state. To send the file to REST service, we have to follow the below steps.

Convert Required file into Bytes

Initially, we have to convert the file into bytes using File Class (which is from System.IO)

  1. //converting Pdf file into bytes array  
  2. var dataBytes = File.ReadAllBytes(reqBook);  

Adding bytes to MemoryStream

Now, create an instance of MemoryStream by passing the byte form of the file.

  1. //adding bytes to memory stream   
  2. var dataStream = new MemoryStream(dataBytes);  

Adding MemoryStream object to the HttpResponseMessage Content

The final step is to add the MemoryStream object to the HttpResponseMessage Content as follows.

  1. httpResponseMessage.Content = new StreamContent(bookStuff);  
Other Mandatory Changes for HttpResponseMessage Headers

We are returning a file here so, to make the client understand the content of the service, we have to modify the following HttpResponseMessage header properties.

  • ContentDisposition
  • FileName
  • ContentType

Following code is used to implement the above 3 fields.

  1. httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");  
  2. httpResponseMessage.Content.Headers.ContentDisposition.FileName = PdfFileName;  
  3. httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");  

We need to talk about the ContentType here. I have used application/octet-stream, whereas in some places, we can see application/pdf, but why I have used it? In a simple way, I can say that when we are sending a file to the REST service and we don’t know the file type but it is a trusted one, in these situations, we have to use application/octet-stream.

Complete Code in a single shot

I have written with IHttpActionResult and HttpResponseMessage action results.

  1. public class EbookController : ApiController  
  2.     {  
  3.         string bookPath_Pdf = @"C:\MyWorkSpace\SelfDev\UserAPI\UserAPI\Books\sample.pdf";  
  4.         string bookPath_xls = @"C:\MyWorkSpace\SelfDev\UserAPI\UserAPI\Books\sample.xls";  
  5.         string bookPath_doc = @"C:\MyWorkSpace\SelfDev\UserAPI\UserAPI\Books\sample.doc";  
  6.         string bookPath_zip = @"C:\MyWorkSpace\SelfDev\UserAPI\UserAPI\Books\";  
  8.         [HttpGet]  
  9.         [Route("Ebook/GetBookFor/{format}")]  
  10.         public IHttpActionResult GetbookFor(string format)  
  11.         {  
  12.             string reqBook = format.ToLower() == "pdf" ? bookPath_Pdf : (format.ToLower() == "xls" ? bookPath_xls : (format.ToLower() == "doc" ? bookPath_doc : bookPath_zip));  
  13.             string bookName = "sample." + format.ToLower();  
  15.             //converting Pdf file into bytes array  
  16.             var dataBytes = File.ReadAllBytes(reqBook);  
  17.             //adding bytes to memory stream   
  18.             var dataStream = new MemoryStream(dataBytes);  
  19.             return new eBookResult(dataStream, Request, bookName);  
  20.         }  
  21.         [HttpGet]  
  22.         [Route("Ebook/GetBookForHRM/{format}")]  
  23.         public HttpResponseMessage GetBookForHRM(string format)  
  24.         {  
  25.             string reqBook = format.ToLower() == "pdf" ? bookPath_Pdf : (format.ToLower() == "xls" ? bookPath_xls : (format.ToLower() == "doc" ? bookPath_doc : bookPath_zip));  
  26.             string bookName = "sample." + format.ToLower();  
  27.             //converting Pdf file into bytes array  
  28.             var dataBytes = File.ReadAllBytes(reqBook);  
  29.             //adding bytes to memory stream   
  30.             var dataStream = new MemoryStream(dataBytes);  
  32.             HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);  
  33.             httpResponseMessage.Content = new StreamContent(dataStream);  
  34.             httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");  
  35.             httpResponseMessage.Content.Headers.ContentDisposition.FileName = bookName;  
  36.             httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");  
  38.             return httpResponseMessage;  
  39.         }  
  40.     }  
  42.     public class eBookResult : IHttpActionResult  
  43.     {  
  44.         MemoryStream bookStuff;  
  45.         string PdfFileName;  
  46.         HttpRequestMessage httpRequestMessage;  
  47.         HttpResponseMessage httpResponseMessage;  
  48.         public eBookResult(MemoryStream data, HttpRequestMessage request, string filename)  
  49.         {  
  50.             bookStuff = data;  
  51.             httpRequestMessage = request;  
  52.             PdfFileName = filename;  
  53.         }  
  54.         public System.Threading.Tasks.Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)  
  55.         {  
  56.             httpResponseMessage = httpRequestMessage.CreateResponse(HttpStatusCode.OK);  
  57.             httpResponseMessage.Content = new StreamContent(bookStuff);  
  58.             //httpResponseMessage.Content = new ByteArrayContent(bookStuff.ToArray());  
  59.             httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");  
  60.             httpResponseMessage.Content.Headers.ContentDisposition.FileName = PdfFileName;  
  61.             httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");  
  63.             return System.Threading.Tasks.Task.FromResult(httpResponseMessage);  
  64.         }  
  65.     }  


I ran the project and tried to download all the books in all formats with the following URLs (your IP may change when you run the code on your system).

  • http://localhost:59217/api/Ebook/GetBookFor?format=pdf
  • http://localhost:59217/api/Ebook/GetBookFor?format=doc
  • http://localhost:59217/api/Ebook/GetBookFor?format=xls
  • http://localhost:59217/api/Ebook/GetBookFor?format=zip

Initially, I have sent the PDF format value to the service and got the PDF file in response.

Later, I requested the Word document.

How to execute the attached source code (Please go through this section if you want to practice this article with the attached project)

I have attached only required files with the actual folder structure (due to the size of the project).

Please follow the below steps to create the file transferrable Web API service.

  • Download the attached project.
  • Open Visual Studio and create New Web API project.
  • Create Book folder at root level in the project.
  • Add any sample pdf, word, excel, zip (name them as sample) files into it.


  • Create a new API controller and Copy the content of EbookController from the downloaded project into it.
  • Please change the books path strings in newly created Controllers.
  • Add the following code to WebAPIConfig.cs
    1. config.Routes.MapHttpRoute(
    2.    name: "FileServiceRoute”,  
    3.    routeTemplate: “api / {controller}/{action}/ {id}”,
    4.    defaults: new {id = RouteParameter.Optional}
    5. );  
  • Rebuild the project and run.
  • Run any of the above URLs with your project IP

You can see downloading of files when you run the URLs.

Up Next
    Ebook Download
    View all
    View all