【问题标题】:Return 404 when using the ProducesAttribute for image/jpg in ASP.Net Core Web APi在 ASP.Net Core Web APi 中为 image/jpg 使用 ProducesAttribute 时返回 404
【发布时间】:2020-07-18 00:40:51
【问题描述】:

我有以下端点应该返回图像。当给定的员工 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")] 属性,它会按预期工作。我的猜测是过滤器对 Content-Type=image/jpg 返回的 404 不满意

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

谢谢

【问题讨论】:

  • 这可能是您使用过滤器的顺序。尝试将[Produces("image/jpg")] 移动到[HttpGet("{employeeId}/images/picture")] 下方,同时交换ProducesResponseType。所以顺序就像 1. HttpGet 2. Produces 3. reponse 200 4. response 404
  • @scircia,谢谢你,但这并没有什么不同。仍然得到 406

标签: c# .net asp.net-core-webapi asp.net-core-3.1


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2017-12-10
    • 2020-07-10
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    相关资源
    最近更新 更多