I am trying to get files from my MVC project (asp.net core 3.1)
I created a link
<a asp-action="@nameof(HomeController.Download)" asp-controller="@HomeController.Name" asp-route-fileName="fileName.doc" download>FileName</a>
I created a controller
public async Task<ActionResult> Download(string fileName) {
var path = Path.Combine(_hostingEnvironment.WebRootPath, fileName);
if (!System.IO.File.Exists(path)) {
return NotFound();
}
var fileBytes = await System.IO.File.ReadAllBytesAsync(path);
var response = new FileContentResult(fileBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
FileDownloadName = fileName
};
return response;
}
In Chrome i get the warning
Download is disallowed. The frame initiating or instantiating the download is sandboxed, but the flag ‘allow-downloads’ is not set. See https://www.chromestatus.com/feature/5706745674465280 for more details.
Following the link, how can i add:
add "allow-downloads" to the sandbox attributes list to opt in
The file is downloaded if i click the button from Microsoft Edge
The sandbox attribute enables an extra set of restrictions for the content in an iframe. When the sandbox attribute is present, and it will: treat the content as being from a unique origin. block form submission. block script execution.
This is what I had to do for my project, hopefully it will point you to the right direction.
In your Startup.cs
services.AddMvc(options =>{
options.Filters.Add(new MyActionFilterAttribute());
}
Then in MyActionFilterAttribute.cs
public class MyActionFilterAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Headers.Add("Content-Security-Policy", "sandbox allow-downloads; " )
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With