Output caching in ASP.NET MVC application
2010-02-21 13:19 AnyKoro 阅读(627) 评论(1) 编辑 收藏 举报Goal: Here, I am going to explain, how we can improve performance of ASP.Net MVC application using output caching.
Advantage:
- It enables us to cache the content returned by Controller action.
- It stops controller action to generate same content each time.
- We can set caching parameter using output cache.
- We can specify where to send caching data. For example web Server or user browser etc.
- 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:
- the web server
- any proxy servers
- 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
- We can store controller action cache in one central location.
- We can create one cache profile and apply the profile to several controllers or controller actions.
- 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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)