Efficiently sending files from asp.net core

帅比萌擦擦* 提交于 2019-12-23 15:38:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44979668/efficiently-sending-files-from-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!