Can an ASP.NET MVC controller return an Image?

前端 未结 19 1682
旧时难觅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:50

    if (!System.IO.File.Exists(filePath))
        return SomeHelper.EmptyImageResult(); // preventing JSON GET/POST exception
    else
        return new FilePathResult(filePath, contentType);
    

    SomeHelper.EmptyImageResult() should return FileResult with existing image (1x1 transparent, for example).

    This is easiest way if you have files stored on local drive. If files are byte[] or stream - then use FileContentResult or FileStreamResult as Dylan suggested.

提交回复
热议问题