从Asp.Net Core WebAPI返回jpeg图像

han*_*ans 38 content-type asp.net-core asp.net-core-webapi

使用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;
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

han*_*ans 61

清洁溶液使用FilestreamResult!!

[HttpGet]
public async Task<IActionResult> Get()
{
    var image = System.IO.File.OpenRead("C:\\test\\random_image.jpeg");
    return File(image, "image/jpeg");
}
Run Code Online (Sandbox Code Playgroud)

说明:

在ASP.NET Core中,您必须使用Controller内部的内置 File()方法.这将允许您手动设置内容类型.

不要HttpResponseMessage像以前在ASP.NET Web API 2中使用那样创建和返回.它不会做任何事情,甚至不会抛出错误!

  • Visual Studio说这种方法缺乏等待使用,因此将同步运行.是否可以缓存文件,以便每次都不必读取?为什么不使用接受文件路径的重载File方法而不是读取文件?如果读取文件为什么不使用`using`语句? (4认同)
  • 将方法从'async Task &lt;IActionResult&gt;'重写为'IActionResult'也可以通过一种更简洁的方式来完成操作(Visual Studio正确地指出此方法中存在异步行为);)... (3认同)
  • 将这一行写成: return await Task.Run(() =&gt; File(image, "image/jpeg")); 为我删除了错误并且也有效。 (2认同)
  • 不要忘记 Dispose OpenRead 对象,但 PhysicalFile 是更好的解决方案。 (2认同)

Ant*_*e V 5

PhysicalFile使用简单的语法帮助从Asp.Net Core WebAPI返回文件

    [HttpGet]
    public IActionResult Get(int imageId)
    {            
       return new PhysicalFile(@"C:\test.jpg", "image/jpeg");
    }
Run Code Online (Sandbox Code Playgroud)

  • 我想知道这是异步的吗?我不想陷入死锁或无法访问的文件? (2认同)