How to download a file in ASP.NET Core

后端 未结 9 1967
离开以前
离开以前 2020-12-02 13:14

In MVC, we have used following code to download a file. In ASP.NET core, how to achieve this?

HttpResponse response = HttpContext.Current.Response;                   


        
9条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 13:33

    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();
    }
    

提交回复
热议问题