MVC-Output Caching


Output Caching in ASP.NET MVC is a technique used to improve the performance of web applications by caching the content generated by action methods. When an action method's output is cached, subsequent requests for that action will return the cached content rather than re-executing the action method and generating the response from scratch. This reduces the processing time and resource usage on the server.

MVC OutputCache

Here's how you can implement Output Caching in MVC

1. Using the OutputCache Attribute

You can use the OutputCache attribute on action methods or controllers to specify caching settings.

Example

public class HomeController : Controller
{
    [OutputCache(Duration = 60, VaryByParam = "none")]
    public ActionResult Index()
    {
        return View();
    }
}
  • In this example, the Index action method's output will be cached for 60 seconds. The VaryByParam property specifies that the cache should not vary based on any parameters.

    2. Cache Duration

    The Duration property specifies the time, in seconds, for which the output should be cached. After this duration, the cache is expired, and the action method will be executed again.

    3. Varying Cache by Parameters

    You can specify that the cache should vary based on parameters using the VaryByParam property.

    Example

    public class HomeController : Controller
    {
        [OutputCache(Duration = 60, VaryByParam = "id")]
        public ActionResult Details(int id)
        {
            return View();
        }
    }
  • In this case, the output will be cached separately for different id values.


  • Next