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 requested:
www.mywebsite.com/resource/image/topbanner
The controller will look up topbanner.png
and send that image directly back to the client.
I've seen examples of this where you have to create a View - I don't want to use a View. I want to do it all with just the Controller.
Is this possible?
To expland on Dyland's response slightly:
Three classes implement the FileResult class:
They're all fairly self explanatory:
FilePathResult
- this is the easiest way and avoids you having to use Streams.FileContentResult
.FileStreamResult
in a similar way to below, but with aMemoryStream
and usingGetBuffer()
.Streams
useFileStreamResult
. It's called a FileStreamResult but it takes aStream
so I'd guess it works with aMemoryStream
.Below is an example of using the content-disposition technique (not tested):
UPDATE: There are better options than my original answer. This works outside of MVC quite well but it's better to stick with the built-in methods of returning image content. See up-voted answers.
You certainly can. Try out these steps:
Here's some sample code:
Hope that helps!
Look at ContentResult. This returns a string, but can be used to make your own BinaryResult-like class.
Solution 1: To render an image in a view from an image URL
You can create your own extension method:
Then use it like:
Solution 2: To render image from database
Create a controller method that returns image data like below
And use it in a view like:
To use an image rendered from this actionresult in any HTML, use
This worked for me. Since I'm storing images on a SQL Server database.
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.Use the base controllers File method.
As a note, this seems to be fairly efficient. I did a test where I requested the image through the controller (
http://localhost/MyController/Image/MyImage
) and through the direct URL (http://localhost/Images/MyImage.jpg
) and the results were:Note: this is the average time of a request. The average was calculated by making thousands of requests on the local machine, so the totals should not include network latency or bandwidth issues.