代码之家  ›  专栏  ›  技术社区  ›  Rod

使用Web API下载文件

  •  0
  • Rod  · 技术社区  · 2 年前

    我采用了Web API模板,并对下载的工作端点进行了细微的更改。

    [HttpGet(Name = "GetWeatherForecast")]
    public FileStream Get()
    {
        var path = @"C:\Users\user1\download.msi";
        return new FileStream(path, FileMode.Open, FileAccess.Read);
    }
    

    这是一个100mb的下载,我得到 Out of memory 当我尝试下载文件时。

    0 回复  |  直到 2 年前
        1
  •  1
  •   shingo    2 年前

    要输出文件,您应该使用 File 方法:

    var f = new FileStream(path, FileMode.Open, FileAccess.Read);
    return File(f, "application/octet-stream");
    

    如果您返回FileStream,我猜ASP.NET会将其视为 special type ,尝试在输出整个对象之前对其进行序列化。