目录(?)[+]

MVC3缓存之一:使用页面缓存

在MVC3中要如果要启用页面缓存,在页面对应的Action前面加上一个OutputCache属性即可。

我们建一个Demo来测试一下,在此Demo中,在View的Home目录下的Index.cshtml中让页面输入当前的时间。

  1. @{
  2. Layout = null;
  3. }
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7. <title>Index</title>
  8. </head>
  9. <body>
  10. <div>
  11. <h2>
  12. 现在时间:@DateTime.Now.ToString("T")</h2>
  13. </div>
  14. </body>
  15. </html>

在Controllers中添加对应的Action,并加上OutputCache属性。

 
  1. [HandleError]
  2. public class HomeController : Controller
  3. {
  4. [OutputCache(Duration = 5, VaryByParam = "none")]
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9. }

刷新页面即可看到页面做了一个5秒的缓存。当页面中数据不是需要实时的呈现给用户时,这样的页面缓存可以减小实时地对数据处理和请求,当然这是针对整个页面做的缓存,缓存的粒度还是比较粗的。

 

缓存的位置

可以通过设置缓存的Location属性,决定将缓存放置在何处。

Location可以设置的属性如下:

· Any
· Client
· Downstream
· Server
· None
· ServerAndClient

Location的默认值为Any。一般推荐将用户侧的信息存储在Client端,一些公用的信息存储在Server端。

加上Location应该像这样。

  1. [HandleError]
  2. public class HomeController : Controller
  3. {
  4. [OutputCache(Duration = 5, VaryByParam = "none", Location = OutputCacheLocation.Client, NoStore = true)]
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9. }

缓存依赖

VaryByParam可以对缓存设置缓存依赖条件,如一个产品详细页面,可能就是根据产品ID进行缓存页面。

缓存依赖应该设置成下面这样。

在MVC3中对输出缓存进行了改进,OutputCache不需要手动指定VaryByParam,会自动使用Action的参数作为缓存过期条件。

  1. [HandleError]
  2. public class HomeController : Controller
  3. {
  4. [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9. }

另一种通用的设置方法

当我们需要对多个Action进行统一的设置时,可以在web.config文件中统一配置后进行应用即可。

在web.config中配置下Caching节点

  1. <caching>
  2. <outputCacheSettings>
  3. <outputCacheProfiles>
  4. <add name="Cache1Hour" duration="3600" varyByParam="none"/>
  5. </outputCacheProfiles>
  6. </outputCacheSettings>
  7. </caching>

那么在Action上使用该配置节点即可,这样的方法对于统一管理配置信息比较方便。

  1. [HandleError]
  2. public class HomeController : Controller
  3. {
  4. [OutputCache(CacheProfile = "Cache1Hour")]
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9. }

MVC3缓存之二:页面缓存中的局部动态

MVC中有一个Post-cache substitution的东西,可以对缓存的内容进行替换。

使用Post-Cache Substitution

  • 定义一个返回需要显示的动态内容string的方法。
  • 调用HttpResponse.WriteSubstitution()方法即可。

示例,我们在Model层中定义一个随机返回新闻的方法。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web;
  4. namespace MvcApplication1.Models
  5. {
  6. public class News
  7. {
  8. public static string RenderNews(HttpContext context)
  9. {
  10. var news = new List<string>
  11. {
  12. "Gas prices go up!",
  13. "Life discovered on Mars!",
  14. "Moon disappears!"
  15. };
  16. var rnd = new Random();
  17. return news[rnd.Next(news.Count)];
  18. }
  19. }
  20. }

然后在页面中需要动态显示内容的地方调用。

 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index" %>
  2. <%@ Import Namespace="MvcApplication1.Models" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml" >
  5. <head runat="server">
  6. <title>Index</title>
  7. </head>
  8. <body>
  9. <div>
  10. <% Response.WriteSubstitution(News.RenderNews); %>
  11. <hr />
  12. The content of this page is output cached.
  13. <%= DateTime.Now %>
  14. </div>
  15. </body>
  16. </html>

如在上面文章中说明的那样,给Controller加上缓存属性。

  1. using System.Web.Mvc;
  2. namespace MvcApplication1.Controllers
  3. {
  4. [HandleError]
  5. public class HomeController : Controller
  6. {
  7. [OutputCache(Duration=60, VaryByParam="none")]
  8. public ActionResult Index()
  9. {
  10. return View();
  11. }
  12. }
  13. }

可以发现,程序对整个页面进行了缓存60s的处理,但调用WriteSubstitution方法的地方还是进行了随机动态显示内容。

 

对Post-Cache Substitution的封装

将静态显示广告Banner的方法封装在AdHelper中。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web;
  4. using System.Web.Mvc;
  5. namespace MvcApplication1.Helpers
  6. {
  7. public static class AdHelper
  8. {
  9. public static void RenderBanner(this HtmlHelper helper)
  10. {
  11. var context = helper.ViewContext.HttpContext;
  12. context.Response.WriteSubstitution(RenderBannerInternal);
  13. }
  14. private static string RenderBannerInternal(HttpContext context)
  15. {
  16. var ads = new List<string>
  17. {
  18. "/ads/banner1.gif",
  19. "/ads/banner2.gif",
  20. "/ads/banner3.gif"
  21. };
  22. var rnd = new Random();
  23. var ad = ads[rnd.Next(ads.Count)];
  24. return String.Format("<img src='{0}' />", ad);
  25. }
  26. }
  27. }

这样在页面中只要进行这样的调用,记得需要在头部导入命名空间。

 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index" %>
  2. <%@ Import Namespace="MvcApplication1.Models" %>
  3. <%@ Import Namespace="MvcApplication1.Helpers" %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  5. <html xmlns="http://www.w3.org/1999/xhtml" >
  6. <head runat="server">
  7. <title>Index</title>
  8. </head>
  9. <body>
  10. <div>
  11. <% Response.WriteSubstitution(News.RenderNews); %>
  12. <hr />
  13. <% Html.RenderBanner(); %>
  14. <hr />
  15. The content of this page is output cached.
  16. <%= DateTime.Now %>
  17. </div>
  18. </body>
  19. </html>

使用这样的方法可以使得内部逻辑对外呈现出更好的封装。

 
 

MVC3缓存之三:MVC3中的局部缓存(Partial Page)

MVC3
版本中,新增了一个叫做Partial
Page的东西,即可以对载入到当前页面的另外的一个View进行缓存后输出,这与我们之前讨论的局部动态刚好相反了,即之前我们进行这个页面的缓存,然
后对局部进行动态输出,现在的解决方案是:页面时动态输出的,而对需要缓存的局部进行缓存处理。查来查去还没有看到局部动态的解决方案,所以我们先看看局
部缓存的处理方法。
 

局部缓存(Partial Page)

我们先建立一个需要局部缓存的页面View,叫做PartialCache.cshtml,页面内容如下:

  1. <p>@ViewBag.Time2</p>

在其对应的Controller中添加对应的Action

  1. [OutputCache(Duration = 10)]
  2. public ActionResult PartialCache()
  3. {
  4. ViewBag.Time2 = DateTime.Now.ToLongTimeString();
  5. return PartialView();
  6. }

我们可以看到对其Action做了缓存处理,对页面进行缓存10秒钟。

而在Index的View中调用此缓存了的页面则需要这样:

  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>
  5. OutputCache Demo</h2>
  6. <p>
  7. No Cache</p>
  8. <div>@DateTime.Now.ToLongTimeString()
  9. </div>
  10. <br />
  11. <p>
  12. Partial Cache 10 mins
  13. </p>
  14. <div class="bar2">@Html.Action("PartialCache", "Index", null)</div>

运行后,我们刷新页面可以发现Index的主体没有缓存,而引用到的PartialCache进行了10秒缓存的处理。

MVC4的缓存的更多相关文章

  1. Mvc4页面缓存设置Cookie导致缓存失效

    [OutputCache(Duration = 60, VaryByParam = "none")]        public ActionResult Index()      ...

  2. ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存

    ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存 part 1:给我点时间,允许我感慨一下2016年 正好有时间,总结一下最近使用的一些技术,也算是为2016年画上一个完 ...

  3. [译]MVC网站教程(四):MVC4网站中集成jqGrid表格插件(系列完结)

    目录 1.   介绍 2.   软件环境 3.   在运行示例代码之前(源代码 + 示例登陆帐号) 4.         jqGrid和AJAX 5.         GridSettings 6.  ...

  4. MVC缓存

    MVC入门系列教程-视频版本,已入驻51CTO学院,文本+视频学效果更好哦.视频链接地址如下: 点我查看视频.另外,针对该系列教程博主提供有偿技术支持,群号:226090960,群内会针对该教程的问题 ...

  5. SignalR + KnockoutJS + ASP.NET MVC4 实现井字游戏

    1.1.1 摘要 今天,我们将使用SignalR + KnockoutJS + ASP.NET MVC实现一个实时HTML5的井字棋游戏. 首先,网络游戏平台一定要让用户登陆进来,所以需要一个登陆模块 ...

  6. 利用CSS预处理技术实现项目换肤功能(less css + asp.net mvc4.0 bundle)

    一.背景 在越来越重视用户体验的今天,换肤功能也慢慢被重视起来.一个web系统用户可以选择一个自己喜欢的系统主题,在用户眼里还是会多少加点分的.我们很开心的是easyui v1.3.4有自带defau ...

  7. MVC缓存OutputCacheAttribute 类提高网站效率(转)

    原文转自:http://www.cnblogs.com/iamlilinfeng/p/4419362.html 命名空间:  System.Web.Mvc 程序集:  System.Web.Mvc(在 ...

  8. MVC4+WebApi+Redis Session共享练习(下)

    上一篇文章我们主要讲解了一些webApi和redis缓存操作,这篇文章我们主要说一些MVC相关的知识(过滤器和错误处理),及采用ajax调用webApi服务. 本篇例子采用的开发环境为:VS2010( ...

  9. MVC4+WebApi+Redis Session共享练习(上)

    这几天生病了,也没有心情写博客,北京医院真心伤不起呀,钱不少花,病没治好,还增加了新病,哎不说了,周末还得去大医院检查一下,趁女盆友还没有回来,把前几天写的东西总结一下.本文也会接触一点webApi的 ...

随机推荐

  1. Exercise02_05

    import java.util.Scanner; public class Rate { public static void main(String[] args){ Scanner input ...

  2. [测试技术分享]DNS域传送漏洞测试

    DNS域传送漏洞测试 1.简介: DNS(Domain Name System)也叫域名管理系统,它它建立在一个分布式数据库基础之上,在这个数据库里,保存了IP地址和域名的相互映射关系.正因为DNS的 ...

  3. Delphi 设置时间格式

    // 设置WINDOWS系统的短日期的格式SetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, 'yyyy-MM-dd'); Applicat ...

  4. Debian安装VirtualBox增强工具

    切换到root用户: apt-get install build-essential 或者 apt-get install gcc make apt-get install dkms apt-get ...

  5. mybatis入门基础----动态SQL

    原文:http://www.cnblogs.com/selene/p/4613035.html 阅读目录 一:动态SQL 二:SQL片段 三:foreach 回到顶部 一:动态SQL 1.1.定义 m ...

  6. [Python爬虫] 之二十七:Selenium +phantomjs 利用 pyquery抓取今日头条视频

    一.介绍 本例子用Selenium +phantomjs爬取今天头条视频(http://www.tvhome.com/news/)的信息,输入给定关键字抓取图片信息. 给定关键字:视频:融合:电视 二 ...

  7. 【转】es6的拓展运算符 spread ...

    原文:https://blog.csdn.net/qq_30100043/article/details/53391308 The rest parameter syntax allows us to ...

  8. Robomongo与MongoDB的故事

    Robomongo,Mongo可视化工具 哇唔,事实上她是三(阴险脸). 你看你看,界面清新,让人家心旷神怡(害羞).谁还想win+R+mongo呀呀呀?! 哎呀呀,继续···说正事. 在这里···借 ...

  9. 正则表达式表示 ja.resx 所在行

    [^\n]*ja.resx[^\n]*\n?正则表达式表示 ja.resx 所在行 用ultraEdit 删除关键字所在行的下一行或是上一行,所在行保留 删除 关键字所在行 的前3行: (^.*?(\ ...

  10. 作为Java程序员应该掌握的10项技能

    本文详细罗列了作为Java程序员应该掌握的10项技能.分享给大家供大家参考.具体如下: 1.语法:必须比较熟悉,在写代码的时候IDE的编辑器对某一行报错应该能够根据报错信息知道是什么样的语法错误并且知 ...