Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently sending files from asp.net core

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?

like image 973
Brandon Petty Avatar asked Jul 07 '17 21:07

Brandon Petty


1 Answers

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.

like image 147
Pradeep Kumar Avatar answered Oct 05 '22 08:10

Pradeep Kumar