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?
You can get image from controller in MVC using the following C# code also public ActionResult GetImage() { string path = Server.MapPath ("~/images/computer.png"); byte [] imageByteData = System.IO.File.ReadAllBytes (path); return File (imageByteData, "image/png"); }
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: cache the image in the case you expect more requests for the image and don't want the disk I/O (my sample doesn't cache it below)
After creating MVC project, open Solution Explorer and add new empty controller. To add new controller, right click on the controller and select Add, then click Controller and create empty controller. I am creating a HomeController. namespace Returning_Image_From_Controller.Controllers
Select Installed Template, Visual C#, then click Web and select ASP.NET Web Application Project. Provide the name for project and click OK. Now one more dialog box will open and from that select Empty Project and check MVC Checkbox and press OK. After creating MVC project, open Solution Explorer and add new empty controller.
Use the base controllers File method.
public ActionResult Image(string id) { var dir = Server.MapPath("/Images"); var path = Path.Combine(dir, id + ".jpg"); //validate the path for security or use other means to generate the path. return base.File(path, "image/jpeg"); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With