Return an image from asp.net web api core as IActionResult

后端 未结 4 835
太阳男子
太阳男子 2021-01-11 16:58

What is the best way to return an image file as IActionResult while using asp.net web api core? I tried returning a base64 string and it works fine. But not considered as ef

4条回答
  •  醉酒成梦
    2021-01-11 17:33

    You can return image using return file with stream or bytes format or using its image path.

    There are few overloaded methods for return File(//parameters); which you can use it in mvc controller's action method.

    API Controller

    [Route("api/[controller]")]
    public class FileController : Controller {
    
        //GET api/file/id
        [HttpGet("{id}"]
        public async Task GetFile(string id) {
            var stream = await {{//__get_stream_here__//}};
            var response = File(stream, "application/octet-stream"); // FileStreamResult
            return response;
        }    
    }
    

    or

    var imageFileStream = System.IO.File.OpenRead("// image path");
    return File(imageFileStream, "image/jpeg");
    

    Hope this will help you.

提交回复
热议问题