Home > DeveloperSection > Forums > Hoe to return image in asp.net mvc?
marcel ethan
marcel ethan

Total Post:105

Points:735
Posted on    November-18-2014 3:05 AM

 ASP.NET MVC C#  ASP.Net  Controller 
Ratings:


 1 Reply(s)
 629  View(s)
Rate this:

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?



Samuel Fernandes
Samuel Fernandes

Total Post:154

Points:1082
Posted on    November-18-2014 6:08 AM

Use the base controllers File method.

public ActionResult Image(string id)

{

    var dir = Server.MapPath("/Images");

    var path = Path.Combine(dir, id + ".jpg");

    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:

  • MVC: 7.6 milliseconds per photo
  • Direct: 6.7 milliseconds per photo

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.


Don't want to miss updates? Please click the below button!

Follow MindStick