In this article I will explain with an example, how to return (download) File using Web API in ASP.Net MVC Razor.
The File will be stored in a Folder (Directory) on Server’s Disk and the File will be downloaded using HttpResponseMessage class object.
Note: For beginners in Web API, please refer my article Step by Step Web API Tutorial for Beginners in ASP.Net MVC.
 
 
File Location
The Files are stored in a Folder (Directory) within the Project Folder as shown below.
Return (Download) File using Web API in ASP.Net MVC
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Web;
using System.Net.Http;
using System.Net.Http.Headers;
 
 
Web API Controller
In order to add a Web API Controller, you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below.
Return (Download) File using Web API in ASP.Net MVC
 
Then give it a suitable name and click Add.
Return (Download) File using Web API in ASP.Net MVC
 
The next task is to register the Configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.
In order to do so open Global.asax file and add the following line.
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
 
Make sure you add it in the same order as shown below.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}
 
The next step is to code the Web API Controller. The Web API Controller consists of a method named GetFile which accepts a String parameter named fileName.
This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpGet attribute which signifies that the method will accept Http Get requests.
First, an object of HttpResponseMessage is created and then the Path of the File is generated by concatenating the Folder (Directory) Path with FileName received.
If the File does not exist then an exception is raised and HttpStatusCode with value NotFound is returned.
If the File exist then the File data is read into an Array of Bytes and it is downloaded to the Client as Attachment using the HttpResponseMessage object.
public class FileAPIController : ApiController
{
    [HttpGet]
    [Route("api/FileAPI/GetFile")]
    public HttpResponseMessage GetFile(string fileName)
    {
        //Create HTTP Response.
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
 
        //Set the File Path.
        string filePath = HttpContext.Current.Server.MapPath("~/Files/") + fileName;
 
        //Check whether File exists.
        if (!File.Exists(filePath))
        {
            //Throw 404 (Not Found) exception if File not found.
            response.StatusCode = HttpStatusCode.NotFound;
            response.ReasonPhrase = string.Format("File not found: {0} .", fileName);
            throw new HttpResponseException(response);
        }
 
        //Read the File into a Byte Array.
        byte[] bytes = File.ReadAllBytes(filePath);
 
        //Set the Response Content.
        response.Content = new ByteArrayContent(bytes);
 
        //Set the Response Content Length.
        response.Content.Headers.ContentLength = bytes.LongLength;
 
        //Set the Content Disposition Header Value and FileName.
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = fileName;
 
        //Set the File Content Type.
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileName));
        return response;
    }
}
 
 
Screenshot
Return (Download) File using Web API in ASP.Net MVC
 
 
Downloads