codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Download Files using Web API

How to return a file from an API endpoint in ASP.NET Core and create an HTML download link.

Changhui Xu
codeburst
Published in
5 min readFeb 22, 2021

--

In this article, I will use a demo Web API application in ASP.NET Core to show you how to transmit files through an API endpoint. In the final HTML page, end users can left-click a hyperlink to download the file or right-click the link to choose “Save Link As” in the context menu and save the file.

The full solution can be found in my GitHub repository, which includes a web project for uploading/downloading files and an integration test project for testing controller methods.

Now let’s dive in.

Return a File in ASP.NET Core Web API

In ASP.NET Core, a Web API action method usually returns an ActionResult object. When we want to return a file response, we can explicitly set the return type for the action method to be FileResult, which is a type inherited from ActionResult. But most times we still want to use the generic ActionResult because it covers many other useful return types, such as BadRequest, NoContent, and so on.

The FileResult type is an abstract type, and it has four concrete implementations: FileContentResult, FileStreamResult, VirtualFileResult, and PhysicalFileResult. These four variants don’t differ much, you can use any of them to construct a FileResult object at your convenience. In other words, no matter which of the four types you use, the client-side will not notice any difference when downloading a file from the API endpoint.

Apart from the constructors for the four concrete types, we can use a method File, provided natively from the ControllerBase class, to return a concrete FileResult object. The File method is very flexible and has a variety of overload methods to instantiate FileContentResult, FileStreamResult, VirtualFileResult, and PhysicalFileResult instances.

With the groundwork laid, we can easily write an action method as follows:

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Changhui Xu

Lead Application Developer. MBA. I write blogs about .NET, Angular, JavaScript/TypeScript, Docker, AWS, DDD, and many others.

Responses (2)

Write a response