使用asp.net核心web api,我想让我的控制器动作方法返回一个jpeg图像流。 在我当前的实现中,浏览器只显示一个json字符串。我的期望是在浏览器中看到图像。
在使用chrome开发人员工具进行调试时,我发现内容类型仍然存在
Content-Type:application/json; charset=utf-8
在响应头中返回,即使在我的代码中我手动将内容类型设置为“image / jpeg”。
寻找解决方案My Web API如下所示
[HttpGet]
public async Task<HttpResponseMessage> Get()
{
var image = System.IO.File.OpenRead("C:\\test\random_image.jpeg");
var stream = new MemoryStream();
image.CopyTo(stream);
stream.Position = 0;
result.Content = new StreamContent(image);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "random_image.jpeg";
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
result.Content.Headers.ContentLength = stream.Length;
return result;
}
清洁解决方案使用FilestreamResult
!!
[HttpGet]
public async Task<IActionResult> Get()
{
var image = System.IO.File.OpenRead("C:\\test\\random_image.jpeg");
return File(image, "image/jpeg");
}
说明:
在ASP.NET Core中,您必须在Controller中使用内置的File()
方法。这将允许您手动设置内容类型。
不要创建和返回HttpResponseMessage
,就像你习惯在ASP.NET Web API 2中使用它一样。它什么都不做,甚至不会抛出错误!
PhysicalFile有助于从语法简单的Asp.Net Core WebAPI返回文件
[HttpGet]
public IActionResult Get(int imageId)
{
return new PhysicalFile(@"C:\test.jpg", "image/jpeg");
}
[HttpGet("Image/{id}")]
public IActionResult Image(int id)
{
if(id == null){ return NotFound(); }
else{
byte[] imagen = "@C:\\test\random_image.jpeg";
return File(imagen, "image/jpeg");
}
}