从asp.net核心高效地发送文件 [英] Efficiently sending files from asp.net core

查看:78
本文介绍了从asp.net核心高效地发送文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣将一些代码移植到ASP.NET Core,并想知道从ASP.NET Core Web服务发送文件(也称为下载"文件)的最有效方法.

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.

使用旧的ASP.NET代码,我正在使用FileStream:

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)
};

但是,我试图找到与FreeBSD的sendfile()等效的.NET,并找到了 HttpResponse.TransmitFile .我认为这样会更快?

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

我还担心,在击中用户之前,该文件将不得不从Kestrel跳到IIS.有什么建议吗?

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?

推荐答案

如果您的意思是将文件流传输到客户端,则可以使用FileResult作为返回类型.

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是所有文件相关操作结果(例如FileContentResult,FileStreamResult,VirtualFileResult,PhysicalFileResult)的父级.请参阅ASP.NET Core ActionResult文档.

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

这篇关于从asp.net核心高效地发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆