How to download a file in ASP.NET Core

后端 未结 9 1991
离开以前
离开以前 2020-12-02 13:14

In MVC, we have used following code to download a file. In ASP.NET core, how to achieve this?

HttpResponse response = HttpContext.Current.Response;                   


        
9条回答
  •  悲哀的现实
    2020-12-02 13:49

    A relatively easy way to achieve this is to use the built-in PhysicalFile result, which is available to all controllers: MS Docs: PhysicalFile

    A simple example:

    public IActionResult DownloadFile(string filePath)
    {
         return PhysicalFile(filePath, MimeTypes.GetMimeType(filePath), Path.GetFileName(filePath));
    }
    

    Now of course you should never expose this kind of API, due to security concerns.

    I typically shield the actual file paths behind a friendly identifier, which I then use to lookup the real file path (or return a 404 if an invalid ID was passed in), ie:

    [HttpGet("download-file/{fileId}")]
    public IActionResult DownloadFile(int fileId)
    {
        var filePath = GetFilePathFromId(fileId);
        if (filePath == null) return NotFound();
    
        return PhysicalFile(filePath, MimeTypes.GetMimeType(filePath), Path.GetFileName(filePath));
    }
    

    For those that are curious, the MimeTypes helper is a great little nuget package from the folks at MimeKit

提交回复
热议问题