Updated on Kisan Patel
In this tutorial, you learn how to implement the OutputCache
attribute to cache results for faster page loads in ASP.NET MVC.
You can cached results by adding the OutputCache
attribute above an action in controller:
[OutputCache (Duration=1000)] public ActionResult Index() { using (StudentContext _db = new StudentContext()) { return View(_db.Students.ToList()); } }
This will cache the results of the view automatically for 1000 seconds and be shared for each use visiting this page. That means if you have 1000 visitors requesting the same page then caching the results can save on thousands of requests to the database, and lower the processing time required by IIS by simply loading an alrealy fully processed view.
By default, if you do not specify any values in the VaryByParam
field, MVC 3 will automatically create one cache entry per unique variable combination.
[OutputCache (Duration=600, VaryByParam="email")] public ActionResult Index(string email) { using (StudentContext _db = new StudentContext()) { return View(_db.Students.Where(x => x.email == email).ToList()); } }
In the above, ASP.NET will cache an instance of the resulting HTML view for each occurrence of email (for example, one for test1@gmail.com, one for test2@gmail.com and so on)
Now, we will also include SQL dependency in web.config as shown in below code:
<connectionStrings> <add name="StudentContext" connectionString="Data Source=KISAN-PC\SQLEXPRESS;Initial Catalog=test;User ID=sa;Password=sa123" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <caching> <sqlCacheDependency enabled="true" pollTime="2000"> <databases> <add name="MVCDateFormatDemo.Models.StudentContext" connectionStringName="StudentContext"/> </databases> </sqlCacheDependency> </caching> <compilation debug="true" targetFramework="4.5" /> ...
In the above code, the pollTime variable is set to 2 seconds, meaning that every 2 seconds, the cache database will be queried for changes.
We will also need to update Global.asax.cs as shown in below code:
protected void Application_Start() { WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); //Insert below code String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["StudentContext"].ConnectionString; System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(connectionString); //Enable Notification for Student Table System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(connectionString, "Student"); }
In the Application_Start
function, the SQL cache dependency must be set up, and each table that requires listening for updates must be set up with the EnableTableForNotifications
function of the SqlCacheDependencyAdmin
class.