Return 来自 Asp.Net Core WebAPI 的 jpeg 图片

Return jpeg image from Asp.Net Core WebAPI

使用 asp.net 核心网络 api,我想让我的控制器操作方法 return 一个 jpeg图像流
在我当前的实现中,浏览器 仅显示 json 字符串 。 我的期望是在浏览器中看到图像。

在使用 chrome 开发者工具进行调试时,我发现内容类型仍然是

Content-Type:application/json; charset=utf-8

return 在响应 header 中输入,即使在我的代码中我手动将内容类型设置为 "image/jpeg"。

寻求解决方案我的网站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 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() 方法。这将允许您手动设置内容类型。

不要创建 return HttpResponseMessage,就像您在 ASP.NET Web API 中习惯使用的那样 2. 它什么都不做,甚至不做抛出错误!!

[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");
        }
    }

PhysicalFile 有助于从 Asp.Net 核心 WebAPI 中提取 return 文件,语法简单

    [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;
}