MVC3缓存之一:使用页面缓存
MVC3缓存之一:使用页面缓存
在MVC3中要如果要启用页面缓存,在页面对应的Action前面加上一个OutputCache属性即可。
我们建一个Demo来测试一下,在此Demo中,在View的Home目录下的Index.cshtml中让页面输入当前的时间。
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <title>Index</title>
- </head>
- <body>
- <div>
- <h2>
- 现在时间:@DateTime.Now.ToString("T")</h2>
- </div>
- </body>
- </html>
在Controllers中添加对应的Action,并加上OutputCache属性。
- [HandleError]
- public class HomeController : Controller
- {
- [OutputCache(Duration = 5, VaryByParam = "none")]
- public ActionResult Index()
- {
- return View();
- }
- }
刷新页面即可看到页面做了一个5秒的缓存。当页面中数据不是需要实时的呈现给用户时,这样的页面缓存可以减小实时地对数据处理和请求,当然这是针对整个页面做的缓存,缓存的粒度还是比较粗的。
缓存的位置
可以通过设置缓存的Location属性,决定将缓存放置在何处。
Location可以设置的属性如下:
Location的默认值为Any。一般推荐将用户侧的信息存储在Client端,一些公用的信息存储在Server端。
加上Location应该像这样。
- [HandleError]
- public class HomeController : Controller
- {
- [OutputCache(Duration = 5, VaryByParam = "none", Location = OutputCacheLocation.Client, NoStore = true)]
- public ActionResult Index()
- {
- return View();
- }
- }
缓存依赖
VaryByParam可以对缓存设置缓存依赖条件,如一个产品详细页面,可能就是根据产品ID进行缓存页面。
缓存依赖应该设置成下面这样。
在MVC3中对输出缓存进行了改进,OutputCache不需要手动指定VaryByParam,会自动使用Action的参数作为缓存过期条件。
- [HandleError]
- public class HomeController : Controller
- {
- [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
- public ActionResult Index()
- {
- return View();
- }
- }
另一种通用的设置方法
当我们需要对多个Action进行统一的设置时,可以在web.config文件中统一配置后进行应用即可。
在web.config中配置下Caching节点
- <caching>
- <outputCacheSettings>
- <outputCacheProfiles>
- <add name="Cache1Hour" duration="3600" varyByParam="none"/>
- </outputCacheProfiles>
- </outputCacheSettings>
- </caching>
那么在Action上使用该配置节点即可,这样的方法对于统一管理配置信息比较方便。
- [HandleError]
- public class HomeController : Controller
- {
- [OutputCache(CacheProfile = "Cache1Hour")]
- public ActionResult Index()
- {
- return View();
- }
- }
MVC3缓存之二:页面缓存中的局部动态
MVC中有一个Post-cache substitution的东西,可以对缓存的内容进行替换。
使用Post-Cache Substitution
- 定义一个返回需要显示的动态内容string的方法。
- 调用HttpResponse.WriteSubstitution()方法即可。
示例,我们在Model层中定义一个随机返回新闻的方法。
- using System;
- using System.Collections.Generic;
- using System.Web;
- namespace MvcApplication1.Models
- {
- public class News
- {
- public static string RenderNews(HttpContext context)
- {
- var news = new List<string>
- {
- "Gas prices go up!",
- "Life discovered on Mars!",
- "Moon disappears!"
- };
- var rnd = new Random();
- return news[rnd.Next(news.Count)];
- }
- }
- }
然后在页面中需要动态显示内容的地方调用。
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index" %>
- <%@ Import Namespace="MvcApplication1.Models" %>
- <!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 runat="server">
- <title>Index</title>
- </head>
- <body>
- <div>
- <% Response.WriteSubstitution(News.RenderNews); %>
- <hr />
- The content of this page is output cached.
- <%= DateTime.Now %>
- </div>
- </body>
- </html>
如在上面文章中说明的那样,给Controller加上缓存属性。
- using System.Web.Mvc;
- namespace MvcApplication1.Controllers
- {
- [HandleError]
- public class HomeController : Controller
- {
- [OutputCache(Duration=60, VaryByParam="none")]
- public ActionResult Index()
- {
- return View();
- }
- }
- }
可以发现,程序对整个页面进行了缓存60s的处理,但调用WriteSubstitution方法的地方还是进行了随机动态显示内容。
对Post-Cache Substitution的封装
将静态显示广告Banner的方法封装在AdHelper中。
- using System;
- using System.Collections.Generic;
- using System.Web;
- using System.Web.Mvc;
- namespace MvcApplication1.Helpers
- {
- public static class AdHelper
- {
- public static void RenderBanner(this HtmlHelper helper)
- {
- var context = helper.ViewContext.HttpContext;
- context.Response.WriteSubstitution(RenderBannerInternal);
- }
- private static string RenderBannerInternal(HttpContext context)
- {
- var ads = new List<string>
- {
- "/ads/banner1.gif",
- "/ads/banner2.gif",
- "/ads/banner3.gif"
- };
- var rnd = new Random();
- var ad = ads[rnd.Next(ads.Count)];
- return String.Format("<img src='{0}' />", ad);
- }
- }
- }
这样在页面中只要进行这样的调用,记得需要在头部导入命名空间。
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index" %>
- <%@ Import Namespace="MvcApplication1.Models" %>
- <%@ Import Namespace="MvcApplication1.Helpers" %>
- <!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 runat="server">
- <title>Index</title>
- </head>
- <body>
- <div>
- <% Response.WriteSubstitution(News.RenderNews); %>
- <hr />
- <% Html.RenderBanner(); %>
- <hr />
- The content of this page is output cached.
- <%= DateTime.Now %>
- </div>
- </body>
- </html>
使用这样的方法可以使得内部逻辑对外呈现出更好的封装。
MVC3缓存之三:MVC3中的局部缓存(Partial Page)
版本中,新增了一个叫做Partial
Page的东西,即可以对载入到当前页面的另外的一个View进行缓存后输出,这与我们之前讨论的局部动态刚好相反了,即之前我们进行这个页面的缓存,然
后对局部进行动态输出,现在的解决方案是:页面时动态输出的,而对需要缓存的局部进行缓存处理。查来查去还没有看到局部动态的解决方案,所以我们先看看局
部缓存的处理方法。
局部缓存(Partial Page)
我们先建立一个需要局部缓存的页面View,叫做PartialCache.cshtml,页面内容如下:
- <p>@ViewBag.Time2</p>
在其对应的Controller中添加对应的Action
- [OutputCache(Duration = 10)]
- public ActionResult PartialCache()
- {
- ViewBag.Time2 = DateTime.Now.ToLongTimeString();
- return PartialView();
- }
我们可以看到对其Action做了缓存处理,对页面进行缓存10秒钟。
而在Index的View中调用此缓存了的页面则需要这样:
- @{
- ViewBag.Title = "Index";
- }
- <h2>
- OutputCache Demo</h2>
- <p>
- No Cache</p>
- <div>@DateTime.Now.ToLongTimeString()
- </div>
- <br />
- <p>
- Partial Cache 10 mins
- </p>
- <div class="bar2">@Html.Action("PartialCache", "Index", null)</div>
运行后,我们刷新页面可以发现Index的主体没有缓存,而引用到的PartialCache进行了10秒缓存的处理。
MVC3缓存之一:使用页面缓存的更多相关文章
- MVC3缓存:使用页面缓存
在以前的WebForm的开发中,在页面的头部加上OutputCache即可启用页面缓存,而在MVC3中,使用了Razor模板引擎的话,该如何使用页面缓存呢?如何启用 在MVC3中要如果要启用页面缓存, ...
- [转载]MVC3缓存:使用页面缓存
在以前的WebForm的开发中,在页面的头部加上OutputCache即可启用页面缓存,而在MVC3中,使用了Razor模板引擎的话,该如何使用页面缓存呢?如何启用 在MVC3中要如果要启用页面缓存, ...
- 缓存:前端页面缓存、服务器缓存(依赖SQL)MVC3
缓存依赖数据库 第一步 1通过vs里面带的命令提示窗口. 2或者.NET Framework 版本 4(64 位系统)条件,%windir%\Microsoft.NET\Framework64\v4. ...
- 探索ASP.NET MVC5系列之~~~5.缓存篇(页面缓存+二级缓存)
其实任何资料里面的任何知识点都无所谓,都是不重要的,重要的是学习方法,自行摸索的过程(不妥之处欢迎指正) 汇总:http://www.cnblogs.com/dunitian/p/4822808.ht ...
- 缓存插件 EHCache 页面缓存CachingFilter
Ehcache基本用法 CacheManager cacheManager = CacheManager.create(); // 或者 cacheManager = CacheManager.get ...
- Yii的缓存机制之页面缓存
页面缓存是不能通过片段缓存来实现的,因为布局和内容不能同时缓存.只能通过过滤器来生成缓存. 实现方法: 在控制器里使用过滤器来实现 function filters (){ return array( ...
- yii2.0缓存篇之页面缓存
页面缓存: 如果整个页面都不会发生改变,就可以使用页面缓存缓存整个页面. public function behaviors(){ //此方法[也叫行为]会提前控制器内其他方法执 ...
- OSCache页面缓存的使用
完成项目时,为了减少对数据库的频繁操作,引出了缓存,缓存分为以下几种: 1.一级缓存 一级缓存的存储域是session,作用于单个的dao 2.二级缓存 二级缓存的存储域是sessionFactory ...
- [转]MVC3缓存之一:使用页面缓存
本文转自:http://www.cnblogs.com/parry/archive/2011/03/19/OutputCache_In_MVC3.html 在以前的WebForm的开发中,在页面的头部 ...
随机推荐
- windows下使用 linux命令好办法
1. 安装下载 CygwinPortable一键安装包.7z 2. 把安装路径下/ [D:\cygwinportable\CygwinPortable\App\Cygwin\bin] 加到 Path ...
- iOS 关于版本升级问题的解决
从iOS8系统开始,用户可以在设置里面设置在WiFi环境下,自动更新安装的App.此功能大大方便了用户,但是一些用户没有开启此项功能,因此还是需要在程序里面提示用户的. 虽然现在苹果审核不能看到版本提 ...
- shell 删除某个目录下的重复文件
#!/bin/bash ls -lS | awk 'BEGIN{ getline; getline; name1=$;size=$; } { name2=$; sizeTmp=$; ){ ; ; if ...
- data:image/png;base64
大家可能注意到了,网页上有些图片的src或css背景图片的url后面跟了一大串字符,比如: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJ ...
- codevs 3165 爱改名的小融2
3149 爱改名的小融 2 http://codevs.cn/problem/3149/ 题目描述 Description Wikioi上有个人叫小融,他喜欢改名.现在他的要求变了,只要是英文字母就是 ...
- 打印机设置(PrintDialog)、页面设置(PageSetupDialog) 及 RDLC报表如何选择指定打印机
如果一台电脑同时连接多个打印机,而且每个打印机使用的纸张大小各不相同(比如:票据打印钱用的小票专用张,办公打印机用的是A4标准纸),在处理打印类的需求时,如果不用代码干预,用户必须每次打印时,都必须在 ...
- js 数组去重
这是一道常见的面试题,最近在做[搜索历史记录]功能也用到,开始用了 indexOf 方法,该方法在 ECMA5才有支持,对于 IE8- 就不支持了. 我们可以自己写一个函数(Array对象的方法都是定 ...
- 我开源了一个ios应用,你们拿去随便玩
今天开源一个ios应用,自己写的,你们拿去随便玩.地址是: https://github.com/huijimuhe/prankPro 光拿来玩不理清个来龙去脉玩的也不开心是吧,那我就给你们摆摆来龙去 ...
- Windows Phone 8 开发资料
Design http://aka.ms/wp8devdesign Develop http://aka.ms/wp8devdoc Test http://aka.ms/wp8testing Publ ...
- 匈牙利算法(codevs2776)
type node=^link; link=record des:longint; next:node; end; var n,m,i,t,num:longint; p:node; nd:..] of ...