Skip to main content

Understanding Caching in Asp.Net MVC

ching is a most important aspect of high-performance web application. Caching provides a way of storing frequently accessed data and reusing that data. Practically, this is an effective way for improving web application’s performance.

Advantage of Caching

  1. Reduce hosting server round-trips

    When content is cached at the client or in proxies, it cause minimum request to server.
  2. Reduce database server round-trips

    When content is cached at the web server, it can eliminate the database request.
  3. Reduce network traffic

    When content is cached at the client side, it it also reduce the network traffic.
  4. Avoid time-consumption for regenerating reusable content

    When reusable content is cached, it avoid the time consumption for regenerating reusable content.
  5. Improve performance

    Since cached content reduce round-trips, network traffic and avoid time consumption for regenerating reusable content which cause a boost in the performance.

Key points about Caching

  1. Use caching for contents that are accessed frequently.
  2. Avoid caching for contents that are unique per user.
  3. Avoid caching for contents that are accessed infrequently/rarely.
  4. Use the VaryByCustom function to cache multiple versions of a page based on customization aspects of the request such as cookies, role, theme, browser, and so on.
  5. For efficient caching use 64-bit version of Windows Server and SQL Server.
  6. For database caching make sure your database server has sufficient RAM otherwise, it may degrade the performance.
  7. For caching of dynamic contents that change frequently, define a short cache–expiration time rather than disabling caching.

Output Cache Filter

The OutputCache filter allow you to cache the data that is output of an action method. By default, this attribute filter cache the data till 60 seconds. After 60 sec, if a call was made to this action then ASP.NET MVC will cache the output again.

Enabling Output Caching

You can enable the output caching for an action method or controller by adding an [OutputCache] attribute as shown below:
  1. [OutputCache(Duration=20, VaryByParam="none")]
  2. public ActionResult Index()
  3. {
  4. ViewBag.Message = DateTime.Now.ToString();
  5. return View();
  6. }
The output of the Index() action method will be cached for 20 seconds. If you will not defined the duration, it will cached it for by default cache duration 60 sec. You can see the cache effect by applying the break point on index method as shown below.
  

OutputCache Filter Parameter

Parameter
Type
Description
CacheProfile
string
Specify the name of the output cache policy which is defined with in <outputCacheSettings> tag of Web.config.
Duration
int
Specify the time in sec to cache the content
Location
OutputCacheLocation
Specify the location of the output to be cached. By default location is Any.
NoStore
bool
Enable/Disable where to use HTTP Cache-Control. This is used only to protect very sensitive data.
SqlDependency
string
Specify the database and table name pairs on which the cache content depends on. The cached data will expire automatically when the data changes in the database.
VaryByContentEncoding
string
Specify the semicolon separated list of character set (Content encoding like gzip and deflate) that the output cache uses to vary the cache content
VaryByCustom
string
Specify the list of custom strings that the output cache uses to vary the cache content.
VaryByHeader
string
Specify the semicolon separated list of HTTP header names that are used to vary the cache content.
VaryByParam
string
Specify the semicolon separated list of form POST or query string parameters that are used to vary the cache content. If not specified, the default value is none.

Output Caching Location

By default, content is cached in three locations: the web server, any proxy servers, and the user's browser. You can control the content's cached location by changing the location parameter of the OutputCache attribute to any of the following values: Any, Client,Downstream, Server, None, or ServerAndClient.
By default, the location parameter has the value Any which is appropriate for most the scenarios. But some times there are scenarios when you required more control over the cached data.
Suppose you want to cache the logged in use information then you should cached the data on client browser since this data is specific to a user. If you will cached this data on the server, all the user will see the same information that is wrong.
You should cache the data on the server which is common to all the users and is sensitive.

Configure Cache Location

For configuring the cache location, you need to add the System.Web.UI namespace on your controller. You can cached the user's personal information in his browser like as below.
  1. [OutputCache(Duration = 7200, Location = OutputCacheLocation.Client, VaryByParam = "none", NoStore = true)]
  2. public ActionResult Index()
  3. {
  4. ViewBag.Message = "Welcome : " + User.Identity.Name;
  5. return View();
  6. }

Comments

Popular posts from this blog

gcAllowVeryLargeObjects Element

There are numerous new features coming with .NET 4.5 and here, on this blog, you can find several posts about it. But the feature we are goint to talk about today is very exciting, because we were waiting for it more than 10 years. Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio 2012, and create C# Console Application, like picture below. First lets create simple struct with two double members like example below: 1 2 3 4 5 6 7 8 9 10 11 12 public struct ComplexNumber {      public double Re;      public double Im;      public ComplexNumber( double re, double im)      {          Re=re;          Im=im;      } } As we know this structure consumes about 16

Support for debugging lambda expressions with Visual Studio 2015

Anyone who uses LINQ (or lambdas in general) and the debugger will quickly discover the dreaded message “Expression cannot contain lambda expressions”. Lack of lambda support has been a limitation of the Visual Studio Debugger ever since Lambdas were added to C# and Visual Basic.  With visual studio 2015 Microsoft has added support for debugging lambda expressions. Let’s first look at an example, and then I’ll walk you through current limitations. Example To try this yourself, create a new C# Console app with this code: using System.Diagnostics; using System.Linq; class Program { static void Main() { float[] values = Enumerable.Range(0, 100).Select(i => (float)i / 10).ToArray(); Debugger.Break(); } } Then compile, start debugging, and add “values.Where(v => (int)v == 3).ToArray()” in the Watch window. You’ll be happy to see the same as what the screenshot above shows you. I am using Visual Studio 2015 Preview and it has some limitations.

How to allow a very large object in .net application?

Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio, and create C# Console Application. Lets create simple struct with two double members like example below: public struct ComplexNumber { public double Re; public double Im; public ComplexNumber(double re, double im) { Re = re; Im = im; } } As we know this structure consumes about 16 bytes of memory. So if we want to create array of this type which consume more than 2GB we need to create array at least with 134217728 instances. So this sample program below creates 130000000 (about 1,97 GB) of array. int maxCount = 130000000; ComplexNumber[] arr = null; try { arr = new ComplexNumber[maxCount]; } catch (Exception ex) { Console.WriteLine(ex.Message); } So if we run t