在我的.Net Core MVC应用程序的wwwroot文件夹中,我有一些图像。我需要将这些图片提供给TopDesk,在那里我可以放置一个嵌入的url。我对Topdesk没有影响力。我只能改变提供图像的方式。
当我使用到图像的直接链接时,它是有效的。图像嵌入
直接url示例:
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);
}
}
但是url
https://my.web.site/api/images/GetImage/image001.jpeg
中的结果
资源被解释为文档,但使用MIME类型传输image/jpeg
图像不显示。当我在Postman中测试url时,它会在没有警告的情况下返回图像。我在这里错过了什么?
不要返回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中将其注册为singleton,如:
services.AddSingleton(new FileExtensionContentTypeProvider());
并将其注入控制器的构造函数中。