In MVC, we have used following code to download a file. In ASP.NET core, how to achieve this?
HttpResponse response = HttpContext.Current.Response;
Example for Asp.net Core 2.1+ (Best practice)
Startup.cs:
private readonly IHostingEnvironment _env;
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
_env = env;
}
services.AddSingleton(_env.ContentRootFileProvider); //Inject IFileProvider
SomeService.cs:
private readonly IFileProvider _fileProvider;
public SomeService(IFileProvider fileProvider)
{
_fileProvider = fileProvider;
}
public FileStreamResult GetFileAsStream()
{
var stream = _fileProvider
.GetFileInfo("RELATIVE PATH TO FILE FROM APP ROOT")
.CreateReadStream();
return new FileStreamResult(stream, "CONTENT-TYPE")
}
Controller will return IActionResult
[HttpGet]
public IActionResult Get()
{
return _someService.GetFileAsStream() ?? (IActionResult)NotFound();
}