Output caching in ASP.NET MVC application

ASP.NET MVC应用性能优化
本文介绍如何使用输出缓存来提升ASP.NET MVC应用的性能。通过缓存控制器操作返回的内容,避免每次请求都重新执行相同的数据库查询,从而减少服务器的工作负担。文中详细解释了如何配置缓存时长及缓存位置。

Goal: Here, I am going to explain, how we can improve performance of ASP.Net MVC application using output caching.

Advantage:

  1. It enables us to cache the content returned by Controller action.
  2.  It stops controller action to generate same content each time.
  3. We can set caching parameter using output cache.
  4. We can specify where to send caching data. For example web Server or user browser etc.
  5. Caching enables us to avoid performing redundant work at server.
    How it helps?

Imagine, for example, that our ASP.NET MVC application displays a list of database records in a view named Display. Normally, each and every time that a user invokes the controller action that returns the Display view, the set of database records must be retrieved from the database by executing a database query.

If, on the other hand, we take advantage of the output cache then we can avoid executing a database query every time any user invokes the same controller action. The view can be retrieved from the cache instead of being regenerated from the controller action.

How to enable Output Caching?

namespace SampleMVC1.Controllers
{
    public class customController:Controller
    {
        [OutputCache (Duration=20, VaryByParam="None" )]
        public ActionResult  display()
       {

            //Response.redirect();

            // ViewData["Message"] = "Welcome to Dhananjay!";
          return Content("I will Kill you MVC");
            //return View();
        }
    }
}

Here, we are enabling Output cache for a controller named customController. In above listing output of display action will be cached for 20 seconds. In above code, we are enabling output cache for display action of customController controller. If we want to enable output caching for entire controller (display), then, we will have to write code as follows

namespace SampleMVC1.Controllers
{
    [OutputCache(Duration = 20, VaryByParam = "None")]
    public class customController:Controller
    {
       // [OutputCache (Duration=20, VaryByParam="None" )]
        public ActionResult  display()
        {

            //Response.redirect();

           // ViewData["Message"] = "Welcome to Dhananjay!";

          return Content("I will Kill you MVC");
            //return View();
        }
    }
}

How to calculate caching duration?

If we want to cache output of controller action for one day then parameter to duration would be calculated as 60 sec * 60 Min * 24 hrs = 86400 seconds.

[OutputCache(Duration = 86400, VaryByParam = "None")]

Where Content is Cached

By default, when we use the [OutputCache] attribute, content is cached in three locations:

  1. the web server
  2. any proxy servers
  3. the web browser.

We can control exactly where content is cached by modifying the Location property of the [OutputCache] attribute.

We can set the Location property to any one of the following values:

  • Any
  • Client
  • Downstream
  • Server
  • None
  • ServerAndClient

By default, the Location property has the value Any. However, there are situations in which you might want to cache only on the browser or only on the server. For example, if we are caching information that is personalized for each user then we should not cache the information on the server. If we are displaying different information to different users then we should cache the information only on the client.

How to create a cache profile?

Cache profile could be created in Web.config file. Creating cache profile in Web.config having many advantages, like

  1. We can store controller action cache in one central location.
  2. We can create one cache profile and apply the profile to several controllers or controller actions.
  3. We can modify Web.config file without recompiling the application.

Cache profile in Web.config file.

    <caching>
      <outputCacheSetting>
        <outputCacheProfile>
          <add name="CacheHour"  duration="3600" />
         </outputCacheProfile>
      </outputCacheSetting>
      </caching>


How to apply cache profile in Controller action?

 

        [OutputCache(Duration = 10, VaryByParam = "none")]

        public ActionResult Index()

        {

            return View();

        }

 


Caching Example:

This caching example will display same time for 10 seconds

Home\Index.Cs

using System.Web.Mvc;

 

namespace MvcApplication1.Controllers

{

    [HandleError]

    public class HomeController : Controller

    {

        [OutputCache(Duration = 10, VaryByParam = "none")]

        public ActionResult Index()

        {

            return View();

        }

 

    }

}

View\Index.CS

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

    <title>Index</title>

</head>

<body>

    <div>

 

    The current time is: <%= DateTime.Now.ToString("T") %>

 

        </div>

</body> </html>

 

转载于:https://www.cnblogs.com/JosephLiu/archive/2010/02/21/1670271.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值