Efficiently sending files from asp.net core

Brandon Petty picture Brandon Petty · Jul 7, 2017 · Viewed 9.2k times · Source

I am interested in porting some code to ASP.NET Core and wanted to know the most efficient way to send files, aka "download" files, from an ASP.NET Core web service.

With my old ASP.NET code, I was using a FileStream:

var content = new FileStream(
    myLocation,
    FileMode.Open, FileAccess.Read, FileShare.Read);

var result = new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new StreamContent(content)
};

However, I was trying to find the .NET equivalent of FreeBSD's sendfile() and found HttpResponse.TransmitFile . I assume this would be faster?

I am also concerned that the file will have to make an extra hop out of Kestrel, to IIS, before hitting the user. Any advice?

Answer

Pradeep Kumar picture Pradeep Kumar · Jul 10, 2017

If you mean streaming the file to the client, you can use the FileResult as your return type.

public FileResult DownloadFile(string id) {
    var content = new FileStream(myLocation,FileMode.Open, FileAccess.Read, FileShare.Read);
    var response = File(content, "application/octet-stream");//FileStreamResult
    return response;
} 

FileResult is the parent of all file related action results such as FileContentResult, FileStreamResult, VirtualFileResult, PhysicalFileResult. Refer to the ASP.NET Core ActionResult documentation.