How to to return an image with Web API Get method

前端 未结 4 1822
自闭症患者
自闭症患者 2020-12-01 08:57

I need to return an image with a Web API Get method. The code below seems to work fine except that I get this message in the Fiddler\'s ImageView window, \"This response is

4条回答
  •  生来不讨喜
    2020-12-01 09:42

    Adding this answer because those comments are easy to miss (like I nearly did).

    Suggested by Jussi Palo (using a PhysicalFileResult):

    [HttpGet]
    public IActionResult Get()
    {        
        return PhysicalFile(@"E:\\Test.jpg", "image/jpeg");
    }
    
    • A nice single liner that handles things like 206 partial.

    Suggested by Tseng (using an overload of the FileContentResult constructor that accepts a stream):

    [HttpGet]
    public IActionResult Get()
    {        
        FileStream stream = File.Open(@"E:\\Test.jpg");
        return File(stream, "image/jpeg");
    }
    
    • Useful if your stream is coming from somewhere else (like an embedded resource).

    For RL remember to check the file/resource exists, and return 404 if not.

提交回复
热议问题