简体   繁体   中英

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

I hae the following endpoint supposed to return image. I want to return a code 404 when there is no image for the given employee id

        [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");
        }

The problem I am having is that this return a HTTP 406 (Not Acceptable) if the file cannot exist. When debugging, I can see it go into the return NotFound() line.

It works as expected if I take out the [Produces("image/jpg")] attribute. My guess is that filter is not happy with a 404 being returned for Content-Type=image/jpg

I giess I could leave it out but I would really like to understand what's happening and see if there is a solution.

Thanks

The Produces attribute is used to specify the data type returned by the operation.

Because you limit the current method to return only the data type of image/jpg , NotFound() will not be allowed to receive, so 406 Not Acceptable message will appear.

To return 404 information normally, add an allowed type application/json to the Produces attribute like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM