How to Implement OutPutCache Action Filter in ASP.NET MVC

This article helps about implementing OutPutCache in MVC application to save action methods output in memory and reduce server processing, database calls.

It describes below parts of Action Filters

  • A. What are action filters in asp.net mvc.
  • B. Inbuilt Action Filters in MVC
  • C. OutPutCache Action filter with example
  • E. Outputcache location

  • A. What are Action filters in asp.net mvc:

    Action filter is an attribute which provides additional functionality to Action method which can be executed on before (OnActionExecuting) or after (OnActionExecuted) actual action method code execution. These Action Filters can be used with Controller and Action Methods.

    You can create your own Action Filter by implementing IActionFilter interface and overriding OnActionExecuting to inject pre processing logic and and OnActionExecuted to post processing logic.


  • Below are some inbuilt Action Filters in MVC

    1. Output Cache: Caches the output of action method for specified amount of time.
    2. Handle error: If used with Action method then handles error if any errof occur with specified action method. If used with controller handles error if error occurred in any of the action method of specified controller.
    3. Authorize: Restrict access to action method or controller for specified users or roles.

  • C.Action filter with example:

    Let’s try to understand Action filter step by step with example. Here we will try to understand action filter wih output cache attribute..

    1. Go to visual studio and create a new ASP.NET MVC application by going to File -> New -> Project and select ASP.NET MVC application and name it to ActionFilterapp and click ok.
    2. In next window choose empty template and view engine as Razor from dropdown. Click ok.
    3. You will be having solution explorer as below:

      asp net mvc action filter solution

    4. Now let’s go ahead and create a controller name it HomeController by right clicking on Controllers folder -> ADD -> Controller. You will be having code file i.e.
                                  
      namespace ActionFilterapp.Controllers
      {
          public class HomeController : Controller
          {
              //
              // GET: /Home/
              public ActionResult Index()
              {
                  return View();
              }
          } 
      }                         
                              
    5. There might be a requirement where you required to cache the out put of Action method for certain amount of time for example in online shopping application, the category names need to get from database for each request. You can save its output in memory by using OutputCache action filters. For more details about Action Filters see ASP.NET MVC Action Filters with Authorization Filter example.
    6. Now! try to understand it with example. In this example we will try to retain the value of time for 20 seconds.
    7. Right click on index method and add view for this action method. You can see your solution explorer with the index.cshtml file under the view folder.

      asp net mvc action filter controller

    8. Now run your application and refresh the page continuously. You can see the time changes when you refresh the page.
    9. ok! now come to home controller and decorate the action method with output cache attribute and with duration of 20 seconds.
    10.                             
      namespace Authfilterapp.Controllers
      {
          public class HomeController : Controller
          {
              public class HomeController : Controller
              {
                  //
                  // GET: /Home/
                  [OutputCache(Duration=20)]
                  public ActionResult Index()
                  {
                      return View();
                  }
              }
          }
      }     
                                  
                              
    11. Now build the solution and try to access the index action and refresh the page continuously. You will see time is not changing for 20 seconds. After 20 Seconds got changed.

      So basically output of Action Method is cached for 20 seconds and after 20 seconds it refresh the output. This is the functionality of output cache attribute


  • Cache duration of OutputCache

    If you do not specify cache duration of OutPutCache attribute, default value is used which is 60 seconds. We can see it by break points in the code.see the below screen shot

    OutPutCache-duaration


  • OutPutCache location

    The default value for OutPutCache location is Any.

    Below are possible values for OutPutCache

    • Any: OutPutCache can be located on client browser, proxy server.
    • Client: Cache will be stored on client browser as private.
    • Downstream: The output cache will be stored in any HTTP 1.1 cache-capable devices other than the origin server.
    • None: The output cache will be disabled.
    • Server: The output cache will be stored on the same webserver where request gets handled.
    • ServerAndClient: The output cache will be stored on the same webserver where request gets handled or client browsers. Proxy server is not allowed.

    You can also create your own custom OutPutCache attribute.

    Below code displays how you can configure Cache Location

        
        using System.Web.Mvc;
        using System.Web.UI;
    
        namespace ActionFilterapp.Controllers
        {
            public class HomeController : Controller
            {
                //
                // GET: /Home/
                [OutputCache(Duration = 20, Location = OutputCacheLocation.Client,
                         VaryByParam = "none", NoStore = true)]
                public ActionResult Index()
                {
                    return View();
                }
            }
        }
                    
         
                    

I think now you are having some idea about caching and outputcache in ASP.NET MVC. If you like it please write comment and feedback.

Download source code.

Speak your mind :
Leave a comment for this article on dotnetbloogers.com
User profile picture on dotnetmentors.com

by bestdotnet at 4/19/2017 1:22:00 AM
Good post, thanks for sharing
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by bestdotnet at 4/19/2017 1:23:00 AM
Good Post
post comment on dotnetmentors.com