问题
我想在我的ASP中返回一个文件。Net Web API控制器,但我所有的方法返回HttpResponseMessage作为JSON。
目前为止的代码
public async Task<HttpResponseMessage> DownloadAsync(string id)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent({{__insert_stream_here__}});
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
}
当我在浏览器中调用这个端点时,Web API将HttpResponseMessage返回为JSON,并将HTTP内容报头设置为application/ JSON。
你可以用这些方法返回FileResult:
1:返回FileStreamResult
[HttpGet("get-file-stream/{id}"]
public async Task<FileStreamResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
Stream stream = await GetFileStreamById(id);
return new FileStreamResult(stream, mimeType)
{
FileDownloadName = fileName
};
}
2:返回FileContentResult
[HttpGet("get-file-content/{id}"]
public async Task<FileContentResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
byte[] fileBytes = await GetFileBytesById(id);
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = fileName
};
}
如果这是ASP.net-Core,那么你混合了web API版本。让动作返回一个派生的IActionResult,因为在当前代码中,框架将HttpResponseMessage作为模型处理。
[Route("api/[controller]")]
public class DownloadController : Controller {
//GET api/download/12345abc
[HttpGet("{id}")]
public async Task<IActionResult> Download(string id) {
Stream stream = await {{__get_stream_based_on_id_here__}}
if(stream == null)
return NotFound(); // returns a NotFoundResult with Status404NotFound response.
return File(stream, "application/octet-stream", "{{filename.ext}}"); // returns a FileStreamResult
}
}
注意:
当响应完成时,框架将处理在这种情况下使用的流。如果使用using语句,流将在响应发送之前被处理,并导致异常或损坏响应。
下面是在.NET Core Web API中返回文件(例如图像文件)的基本示例:
<img src="@Url.Action("RenderImage", new { id = id})" alt="No Image found" />
下面是将文件从控制器返回到视图的代码。下面是Action方法,它将返回文件:
[Route("api/[controller]")]
public class DownloadController : Controller
{
//GET api/download/123
[HttpGet]
public async Task<IActionResult> RenderImage(string userId)
{
//get Image file using _fileservice from db
var result = await _fileService.getFile(userId);
if (result.byteStream == null)
return NotFound();
return File(result.byteStream, result.ContentType, result.FileName);
}
}
注意:
我们的文件应该首先转换为byte[],然后在数据库中保存为varbinary(max),以便检索。