Returning binary file from controller in ASP.NET Web API

后端 未结 8 784
离开以前
离开以前 2020-11-22 02:55

I\'m working on a web service using ASP.NET MVC\'s new WebAPI that will serve up binary files, mostly .cab and .exe files.

The following co

8条回答
  •  盖世英雄少女心
    2020-11-22 03:48

    For those using .NET Core:

    You can make use of the IActionResult interface in an API controller method, like so...

        [HttpGet("GetReportData/{year}")]
        public async Task GetReportData(int year)
        {
            // Render Excel document in memory and return as Byte[]
            Byte[] file = await this._reportDao.RenderReportAsExcel(year);
    
            return File(file, "application/vnd.openxmlformats", "fileName.xlsx");
        }
    

    This example is simplified, but should get the point across. In .NET Core this process is so much simpler than in previous versions of .NET - i.e. no setting response type, content, headers, etc.

    Also, of course the MIME type for the file and the extension will depend on individual needs.

    Reference: SO Post Answer by @NKosi

提交回复
热议问题