c# - 在 ASP.Net Core Web APi 中为 image/jpg 使用 ProducesAttribute 时返回 404
问题描述
我有以下端点应该返回图像。当给定的员工 ID 没有图像时,我想返回代码 404
[HttpGet("{employeeId}/images/picture")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status200OK)]
[Produces("image/jpg")]
public ActionResult GetImage(int employeeId)
{
var fileName = _employeeService.GetImage(employeeId);
if (fileName == null)
{
return NotFound();
}
return PhysicalFile(fileName, "image/jpg", $"{employeeId}-picture.jpg");
}
我遇到的问题是,如果文件不存在,这将返回 HTTP 406(不可接受)。调试时,我可以看到它进入了return NotFound()
行。
如果我取出[Produces("image/jpg")]
属性,它会按预期工作。我的猜测是过滤器对返回的 404 不满意Content-Type=image/jpg
我想我可以把它排除在外,但我真的很想了解正在发生的事情,看看是否有解决方案。
谢谢
解决方案
Produces属性用于指定操作返回的数据类型。
因为你限制当前方法只返回数据类型image/jpg
,NotFound() 将不允许接收,所以406 Not Acceptable
会出现消息。
要正常返回 404 信息,请将允许的类型添加application/json
到 Produces 属性,如下所示:
[Produces("image/jpg", "application/json")]
推荐阅读
- reactjs - 使用 React 和 Formik 处理错误
- python - 检查是否存在特定选项卡或小节
- scala - 使用 TLS 配置 TheHive
- javascript - currentUser 在 firebase 9 中不起作用或不存在
- java - Akka http scala 服务中的锯齿形堆内存模式
- swift - 新的视图控制器在 iPad 上以模态显示而不是全屏显示
- brightway - 自创过程的nan分数
- python - 如何用 Pandas 融化多索引行并维护列中的索引信息?
- wordpress - 访问令牌已过期 PowerBI WordPress
- azure - graphClient.Directory.AdministrativeUnits