In this article I will explain with an example, how to download file as attachment in browser in ASP.Net Core Razor Pages.
Location of the File
The File to be downloaded is stored in the Files Folder (Directory) inside the wwwroot Folder (Directory).
Razor PageModel (Code-Behind)
The PageModel consists of the following Handler methods.
Handler method for handling GET operation
This Handler method is left empty as it is not required.
Handler method for handling File Download POST operation
This Handler method is called when Download button is clicked.
Inside this Handler method, the path of the File to be downloaded is fetched from wwwroot Folder (Directory) using IWebHostEnvironment interface.
Then, the File is read as Binary Data into a BYTE Array using the ReadAllBytes method of the File class.
Finally, the BYTE Array is sent for download with content type as octet-stream using the File function.
public class IndexModel : PageModel
{
private IWebHostEnvironment Environment { get; set; }
public IndexModel(IWebHostEnvironment _environment)
{
this.Environment = _environment;
}
public void OnGet()
{
}
public FileResult OnPostDownload()
{
//Build the File Path.
string path = Path.Combine(this.Environment.WebRootPath, "Files\\Sample.pdf");
//Read the File data into Byte Array.
byte[] bytes = System.IO.File.ReadAllBytes(path);
//Send the File to Download.
return File(bytes, "application/octet-stream", "Sample.pdf");
}
}
Razor Page (HTML)
Inside the HTML of Razor Page, the ASP.Net TagHelpers is inherited.
The HTML of Razor Page consists of an HTML Form which has been created using the ASP.Net TagHelpers with the following attribute.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of an HTML INPUIT Submit button.
Submitting the Form
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostDownload but here it will be specified as Download when calling from the Razor HTML Page.
@page
@model Download_File_Browser_Core_Razor.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post">
<input type="submit" value="Download" asp-page-handler="Download" />
</form>
</body>
</html>
Screenshot
Demo
Downloads