Return 在 ASP.Net Core Web APi 中为 image/jpg 使用 ProducesAttribute 时出现 404

Return 404 when using the ProducesAttribute for image/jpg in ASP.Net Core Web APi

我有以下端点应该 return 图片。当给定员工 ID

没有图像时,我想 return 代码 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");
        }

我遇到的问题是,如果文件不存在,这个 return HTTP 406(不可接受)。 调试时,我可以看到它进入 return NotFound() 行。

如果我去掉 [Produces("image/jpg")] 属性,它会按预期工作。我的猜测是过滤器不满意 returned Content-Type=image/jpg

的 404

我想我可以省略它,但我真的很想了解发生了什么,看看是否有解决方案。

谢谢

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

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

为了return 404信息正常,在Produces属性中添加一个允许的类型application/json,像这样:

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