Can an ASP.NET MVC controller return an Image?

前端 未结 19 1645
旧时难觅i
旧时难觅i 2020-11-22 02:10

Can I create a Controller that simply returns an image asset?

I would like to route this logic through a controller, whenever a URL such as the following is requeste

19条回答
  •  情深已故
    2020-11-22 02:55

    This worked for me. Since I'm storing images on a SQL Server database.

        [HttpGet("/image/{uuid}")]
        public IActionResult GetImageFile(string uuid) {
            ActionResult actionResult = new NotFoundResult();
            var fileImage = _db.ImageFiles.Find(uuid);
            if (fileImage != null) {
                actionResult = new FileContentResult(fileImage.Data,
                    fileImage.ContentType);
            }
            return actionResult;
        }
    

    In the snippet above _db.ImageFiles.Find(uuid) is searching for the image file record in the db (EF context). It returns a FileImage object which is just a custom class I made for the model and then uses it as FileContentResult.

    public class FileImage {
       public string Uuid { get; set; }
       public byte[] Data { get; set; }
       public string ContentType { get; set; }
    }
    

提交回复
热议问题