Skip to main content
 首页 » 编程设计

c#之如何在 ASP.NET Core 中下载文件

2024年12月31日22leader

在 MVC 中,我们使用以下代码下载文件。在 ASP.NET 核心中,如何实现这一点?

    HttpResponse response = HttpContext.Current.Response;                  
    System.Net.WebClient net = new System.Net.WebClient(); 
    string link = path; 
    response.ClearHeaders(); 
    response.Clear(); 
    response.Expires = 0; 
    response.Buffer = true; 
    response.AddHeader("Content-Disposition", "Attachment;FileName=a"); 
    response.ContentType = "APPLICATION/octet-stream"; 
    response.BinaryWrite(net.DownloadData(link)); 
    response.End(); 

请您参考如下方法:

您的 Controller 应该返回 IActionResult ,并使用 File方法,例如:

[HttpGet("download")] 
public IActionResult GetBlobDownload([FromQuery] string link) 
{ 
    var net = new System.Net.WebClient(); 
    var data = net.DownloadData(link); 
    var content = new System.IO.MemoryStream(data); 
    var contentType = "APPLICATION/octet-stream"; 
    var fileName = "something.bin"; 
    return File(content, contentType, fileName); 
}