.Net Core-通过api发送图像=将资源解释为文档,但以MIME类型image / jpeg传输

问题描述

在.Net Core MVC应用程序的wwwroot文件夹中,我有一些图像。我需要将这些图片提供给TopDesk,然后在其中放置嵌入的URL。我对Topdesk没有任何影响。我只能更改图片的投放方式。

当我使用直接链接到图像时,它可以工作。图片被嵌入

直接网址示例:

https://my.web.site/images/image001.jpeg

但是嵌入尺寸有限(600px),因此我需要调整图像大小。为此,我编写了一个非常简单的api控制器:

[HttpGet]
[Route("api/Images/Getimage/{id}")]
public IActionResult Getimage(string id)
{
    try
    {
      var pad = $"c:\\Images\\{id}";
      if(System.IO.File.Exists(path))
      {
          var fileBytes = System.IO.File.ReadAllBytes(path);
          var smallImage = ..... doing resizing;
          new FileExtensionContentTypeProvider().TryGetContentType(Path.GetFileName(path),out var contentType);
          return File(smallImage,contentType ?? "application/octet-stream",$"{id}");
      }
      return NotFound();
    }
    catch(Exception ex)
    {
        return BadRequest(ex.Message);
    }
}

但网址

https://my.web.site/api/images/Getimage/image001.jpeg

产生

资源被解释为文档,但以MIME类型传输 图片/ jpeg

图像不显示。 当我在Postman中测试网址时,它会返回图像而不会发出警告。 我在这里想念什么?

解决方法

尝试返回File而不是返回FileContentResult

[HttpGet]
[Route("api/Images/GetImage/{id}")]
public IActionResult GetImage(string id)
{
  try
  {
    var path = $"c:\\Images\\{id}";
    if(System.IO.File.Exists(path))
    {
      var fileBytes = System.IO.File.ReadAllBytes(path);
      var smallImage = ..... doing resizing;
      new FileExtensionContentTypeProvider().TryGetContentType(Path.GetFileName(path),out var contentType);
      return new FileContentResult(fileBytes,contentType ?? "application/octet-stream");
    }
  return NotFound();
  }
  catch(Exception ex)
  {
    return BadRequest(ex.Message);
  }
}

使用浏览器导航到/GetImage/{id}时,您会看到使用File时浏览器倾向于下载文件,但是使用FileContentResult时它将直接在浏览器标签中显示图像,这与使用静态文件的行为相同。这可能是由于使用File / FileContentResult(可能是Content-Disposition标头)时添加了响应标头引起的。不确定TopDesk如何使用这些图像。

离题:不对每个请求都实例化FileExtensionContentTypeProvider也是一种好习惯。相反,您可以在Startup.cs中将其注册为单例,例如:

services.AddSingleton(new FileExtensionContentTypeProvider());

并将其注入到控制器的构造函数中。