首页 > 解决方案 > 在 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

我想我可以把它排除在外,但我真的很想了解正在发生的事情,看看是否有解决方案。

谢谢

标签: c#.netasp.net-core-webapiasp.net-core-3.1

解决方案


Produces属性用于指定操作返回的数据类型。

因为你限制当前方法只返回数据类型image/jpg,NotFound() 将不允许接收,所以406 Not Acceptable会出现消息。

要正常返回 404 信息,请将允许的类型添加application/json到 Produces 属性,如下所示:

[Produces("image/jpg", "application/json")]

推荐阅读