Jonathan Wood
Jonathan Wood

Reputation: 67193

Unable to download physical file in Razor Pages

I have a physical file that I want the user to be able to download. The file is in the same folder as my current Razor Page. Here's what I've tried.

First Method: Page Handler

Markup

<a asp-page-handler="DownloadHelp" title="Template Help"><img src="~/images/help.png" /></a>

Code

public IActionResult OnGetDownloadHelp(
{
    return File("TemplateHelp.pdf", MediaTypeNames.Application.Pdf);
}

Result

I get an error that says TemplateHelp.pdf was not found. Strangely, the exception stops on the line await next.Invoke(context); in one of my middleware classes. I'm not sure why the exception appears to be occurring there.

Second Method: Markup Only

Markup

<a download href="TemplateHelp.pdf" title="Download Template Documentation"><img src="~/images/help.png" /></a>

Result

The filename appears in the list of downloads but says Couldn't download - No file.

enter image description here

This seems like it should be straight forward. Does anyone know how to do this?

Upvotes: 0

Views: 90

Answers (3)

Fengzhi Zhou
Fengzhi Zhou

Reputation: 1637

By default, only files in the wwwroot folder are accessible via a direct request.

From comprehension of the MS document, Razor Pages are primarily used to handle dynamic content, while static content (like PDF) should be served from the wwwroot directory unless special routing or middleware are configured.

The design is intended to protect application code and other non-static files from being exposed. Files outside of wwwroot are not automatically accessible via URL. https://learn.microsoft.com/en-us/aspnet/core/fundamentals/file-providers?view=aspnetcore-8.0

Could try PageContext.HttpContext.Request.Path to get the current path.

Upvotes: 0

professional_gambler
professional_gambler

Reputation: 44

Where is your file being stored in your application? In cases like this, it is better to specify the full path of the file being downloaded. Maybe the error is because the application couldn't find the file specified?

The code should look like this:

public IActionResult OnGetDownloadHelp()
{
  byte[] file = System.IO.File.ReadAllBytes("your_path_to_the_file.pdf");
  var contentDisposition = new ContentDispositon();
  contentDisposition.Inline = false;
  Response.Headers.Add("content-disposition", contentDisposition.ToString());
  return File(file,"application/pdf");
}

The inline parameter can automatically download/not download the file in your local system depending on its value. True for not automatic download, and false for automatic download.

I hope this helps!

Upvotes: 0

Efraim Newman
Efraim Newman

Reputation: 1041

The file needs to be in the path of the static files (usually wwwroot), this is the place where asp.net searches for static files and can serve them to the client.

Upvotes: 0

Related Questions