If this is asp.net-core then you are mixing web api versions. have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model.
[Route("api/[controller]")]
public class DownloadController : Controller
{
//GET api/download/12345abc
[HttpGet("{id}"]
public async Task<IActionResult> Download(string id)
{
var stream = await { { __get_stream_here__} }
var response = File(stream, "application/octet-stream");
// FileStreamResult
return response;
}
}
2. return excel file
[Route("api/[controller]")]
[ApiController]
public class ExecelController : ControllerBase
{
//come from:
[Route("api/Execel/TOExecel")]
public IActionResult TOExecel()
{
var list = new List<Test>();
list.Add(new Test()
{
Id = 1,
Name = "Test",
Age = 22,
});
byte[] fileContents;
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(".Net Core 导出");
worksheet.Cells[1, 1].Value = "序号";
worksheet.Cells[1, 2].Value = "Id";
worksheet.Cells[1, 3].Value = "名称";
worksheet.Cells[1, 4].Value = "年龄";
int i = 2;
foreach (var item in list)
{
worksheet.Cells["A" + i].Value = i - 1;
worksheet.Cells["B" + i].Value = item.Id;
worksheet.Cells["C" + i].Value = item.Name;
worksheet.Cells["D" + i].Value = item.Age;
i = i + 1;
}
fileContents = package.GetAsByteArray();
if (fileContents == null || fileContents.Length == 0)
{
return NotFound();
}
}
return File(fileContents, "application/ms-excel", $"{Guid.NewGuid().ToString()}.xlsx");
}
}
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
MIME Types for files upload and download
Below are a few examples of MIME – content types for your information.
Text File – “text/plain“
PNG image – “image/png“
JPEG image – “image/jpeg“
MSDoc – “application/vnd.ms-word“
MSDoc – “application/vnd.ms-word“
PDF file – “application/pdf“
Excel File- “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet“
Difference between FileContentResult FileStreamResult
FileResult – As we know FileResult an abstract base class. Both FileContentResult & FileStreamResult classes are derived class from Abstract FileResult class.
FileStreamResult – Sends binary content to the response by using a Stream instance. Here you have a stream and want to return stream content as a file.
FileContentResult – Sends the contents of a binary file to the response. Here you have a byte array and want to return byte content as a file.