6

I am creating a website with MVC 4. For project requirements, the images are stored in database. I have a View that I bind the Model in which I have the Id of the picture accompanying the story, then I get the image:

View:

<img src='<%= Url.Action("ShowImagen", "Home", new {id = item.IdImagen}) %>' style="width: 300px;
                        height: 200px;" />

Controller:

public FileResult ShowImagen(int id)
    {
        if (id > 0)
        {
            var imageData = new NoticiaRepository().GetImagen(id);
            return File(imageData, "image/jpg");
        }
        else
        {
            return null;
        }           
    }

With this and checking it with Chrome, I've noticed that when I reload the page, It not load the images from the cache, like other files as .css or other images loaded from file system.

Is there any way to make these images are cached? A greeting and thanks.

Dani
  • 65
  • 1
  • 6

2 Answers2

15

You could decorate your ShowImagen controller action with the [OutputCache] attribute:

[OutputCache(Duration = 3600, Location = OutputCacheLocation.Client, VaryByParam = "id")]
public ActionResult ShowImagen(int id)
{
    ...
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thank's, I tried whith OutputCache, but not with the Location parameter. – Dani Mar 05 '13 at 16:28
  • @darin-dimitrov And how can you invalidate the cache at some point? ( e.g. if the content of the one image changes ) – RazvanR Nov 01 '17 at 12:35
  • Old post, but still helpful. Just for the record, for Dotnet Core, the attribute is now `ResponseCache` – Nieminen Aug 28 '18 at 04:00
0

Have you tried decorating your action method with OutputCache attribute?

Daniel Liuzzi
  • 16,807
  • 8
  • 52
  • 57