4

This is my first question on stackOverflow. After many research i don't find a way to download a file when the user go on the right URL.

With .Net Framework is used the following code :

        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    response.ContentType = "text/plain";
    response.AddHeader("Content-Disposition", 
                       "attachment; filename=" + fileName + ";");
    response.TransmitFile(Server.MapPath("FileDownload.csv"));
    response.Flush();    
    response.End();

What is the equivalent with .Net core ? Thanks

Dorian Coulon
  • 204
  • 1
  • 4
  • 14

1 Answers1

12

If you already have a controller, add an Action that return PhysicalFile for file on your disc or File for binary file in memeory:

[HttpGet]
public ActionResult Download(string fileName) {
    var path = @"c:\FileDownload.csv";
    return PhysicalFile(path, "text/plain", fileName);
}

To file path from project folder inject IHostingEnvironment and get WebRootPath (wwroot folder) or ContentRootPath (root project folder).

    var fileName = "FileDownload.csv";
    string contentRootPath = _hostingEnvironment.ContentRootPath;
    return PhysicalFile(Path.Combine(contentRootPath, fileName);, "text/plain", fileName);
Ivvan
  • 720
  • 11
  • 24
  • I'm using razor pages, so there is no controler. – Dorian Coulon Nov 20 '18 at 15:23
  • The idea still the same, almost no differences, just follow razor pages convention - no attribute on method and use handler to call the method, like 'OnGetFileDownload'. Still you can pass the parameter and you have access to the helper method `PhysicalFile`. – Ivvan Nov 20 '18 at 15:36