使用 asp.net core web api,我想让我的控制器操作方法返回一个 jpeg 图像流。在我当前的实现中,浏览器只显示一个 json 字符串。我的期望是在浏览器中看到图像。
在使用 chrome 开发者工具进行调试时,我发现内容类型仍然是
Content-Type:application/json; charset=utf-8
在响应标头中返回,即使在我的代码中我手动将内容类型设置为“image/jpeg”。
寻找解决方案 我的 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;
}
https://i.stack.imgur.com/bMt50.png
清洁解决方案使用FilestreamResult
!
[HttpGet]
public IActionResult Get()
{
var image = System.IO.File.OpenRead("C:\\test\\random_image.jpeg");
return File(image, "image/jpeg");
}
解释:
在 ASP.NET Core 中,您必须在 Controller 中使用 built-in File()
方法。这将允许您手动设置内容类型。
不要创建并返回 HttpResponseMessage
,就像您过去在 ASP.NET Web API 2 中使用的那样。它什么都不做,甚至不会抛出错误!
PhysicalFile 有助于从 Asp.Net Core WebAPI 返回文件,语法简单
[HttpGet]
public IActionResult Get(int imageId)
{
return PhysicalFile(@"C:\test.jpg", "image/jpeg");
}
就我而言,我使用的是图像的相对路径,所以以下是我的工作解决方案
[HttpGet]
public async Task<IActionResult> Get()
{
var url = "/content/image.png";
var path = GetPhysicalPathFromURelativeUrl(url);
return PhysicalFile(image, "image/png");
}
public string GetPhysicalPathFromRelativeUrl(string url)
{
var path = Path.Combine(_host.Value.WebRootPath, url.TrimStart('/').Replace("/", "\\"));
return path;
}
[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");
}
}
using
语句?