Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC caching database images

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.

like image 925
Dani Avatar asked Mar 05 '13 15:03

Dani


People also ask

What is caching in MVC?

Learn Caching in Asp.net MVC, How to use Caching in Asp.net MVC to improve performance. Caching Implementation: Caching is a technique which stores data in memory that is being used frequently, Caching is used to improve the performance in ASP.NET MVC Application

How to cache data in ASP NET MVC?

Always use caching with images or media files. Generally, we can cache our data using 3 ways in ASP.NET MVC. Caching whole or partial page response using OutputCache Attribute While designing any website, we have to use static content.

How to use outputcache attribute in MVC?

In ASP.NET MVC, we can cache page response using "OutputCache" attribute. This type of caching is basically used to cache your content generated by an action method. "OutputCache" attribute can be used with activity level or controller level. In Output Caching, we can define the age of caching using duration in seconds.

What is distributed caching in ASP NET Core?

The cache is shared across the servers that process requests. A client can submit a request that's handled by any server in the group if cached data for the client is available. ASP.NET Core works with SQL Server, Redis, and NCache distributed caches. For more information, see Distributed caching in ASP.NET Core.


1 Answers

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

[OutputCache(Duration = 3600, Location = OutputCacheLocation.Client, VaryByParam = "id")]
public ActionResult ShowImagen(int id)
{
    ...
}
like image 50
Darin Dimitrov Avatar answered Sep 28 '22 07:09

Darin Dimitrov