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

Boursomaster
  • 202
  • 1
  • 5
  • 15

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
  • 25
  • I'm using razor pages, so there is no controler. – Boursomaster 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
  • What does "text/plain" do in your code? Sorry I'm trying to understand it – DialFrost Aug 16 '22 at 05:08
  • 1
    @DialFrost this is [media type](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Configuring_server_MIME_types) witch will be returned in [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) header to the client, so it can interpret the result correctry. In this case browser will show entire file content as plain text without any styles and scripts. – Ivvan Aug 16 '22 at 13:03