静态化处理,可以大大提高客户的访问浏览速度,提高用户体验,同时也降低了服务器本身的压力。在asp.net mvc3中,可以相对容易地处理静态化问题,不用过多考虑静态网页的同步,生成等等问题。我提供这个方法很简单,就需要在需要静态化处理的Controller或Action上加一个Attribute就可以。下面是我写的一个生成静态文件的ActionFilterAttribute。

1     using System;


  2     using System.IO;
  3     using System.Text;
  4     using System.Web;
  5     using System.Web.Mvc;
  6     using NLog;
  7 
  8     /// <summary>
  9     /// 生成静态文件
 10     /// </summary>
 11     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
 12     public class GenerateStaticFileAttribute : ActionFilterAttribute
 13     {
 14         #region 私有属性
 15 
 16         private static readonly Logger logger = LogManager.GetCurrentClassLogger();
 17 
 18         #endregion
 19 
 20         #region 公共属性
 21 
 22         /// <summary>
 23         /// 过期时间,以小时为单位
 24         /// </summary>
 25         public int Expiration { get; set; }
 26 
 27         /// <summary>
 28         /// 文件后缀名
 29         /// </summary>
 30         public string Suffix { get; set; }
 31 
 32         /// <summary>
 33         /// 缓存目录
 34         /// </summary>
 35         public string CacheDirectory { get; set; }
 36 
 37         /// <summary>
 38         /// 指定生成的文件名
 39         /// </summary>
 40         public string FileName { get; set; }
 41 
 42         #endregion
 43 
 44         #region 构造函数
 45 
 46         /// <summary>
 47         /// 默认构造函数
 48         /// </summary>
 49         public GenerateStaticFileAttribute()
 50         {
 51             Expiration = 1;
 52             CacheDirectory = AppDomain.CurrentDomain.BaseDirectory;
 53         }
 54 
 55         #endregion
 56 
 57         #region 方法
 58 
 59         public override void OnResultExecuted(ResultExecutedContext filterContext)
 60         {
 61             var fileInfo = GetCacheFileInfo(filterContext);
 62 
 63             if ((fileInfo.Exists && fileInfo.CreationTime.AddHours(Expiration) < DateTime.Now) || !fileInfo.Exists)
 64             {
 65                 var deleted = false;
 66 
 67                 try
 68                 {
 69                     if (fileInfo.Exists)
 70                     {
 71                         fileInfo.Delete();
 72                     }
 73 
 74                     deleted = true;
 75                 }
 76                 catch (Exception ex)
 77                 {
 78                     logger.Error("删除文件:{0}发生异常:{1}", fileInfo.FullName, ex.StackTrace);
 79                 }
 80 
 81                 var created = false;
 82 
 83                 try
 84                 {
 85                     if (!fileInfo.Directory.Exists)
 86                     {
 87                         fileInfo.Directory.Create();
 88                     }
 89 
 90                     created = true;
 91                 }
 92                 catch (IOException ex)
 93                 {
 94                     logger.Error("创建目录:{0}发生异常:{1}", fileInfo.DirectoryName, ex.StackTrace);
 95                 }
 96 
 97                 if (deleted && created)
 98                 {
 99                     FileStream fileStream = null;
100                     StreamWriter streamWriter = null;
101 
102                     try
103                     {
104                         var viewResult = filterContext.Result as ViewResult;
105                         fileStream = new FileStream(fileInfo.FullName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
106                         streamWriter = new StreamWriter(fileStream);
107                         var viewContext = new ViewContext(filterContext.Controller.ControllerContext, viewResult.View, viewResult.ViewData, viewResult.TempData, streamWriter);
108                         viewResult.View.Render(viewContext, streamWriter);
109                     }
110                     catch (Exception ex)
111                     {
112                         logger.Error("生成缓存文件:{0}发生异常:{1}", fileInfo.FullName, ex.StackTrace);
113                     }
114                     finally
115                     {
116                         if (streamWriter != null)
117                         {
118                             streamWriter.Close();
119                         }
120 
121                         if (fileStream != null)
122                         {
123                             fileStream.Close();
124                         }
125                     }
126                 }
127             }
128         }
129 
130         /// <summary>
131         /// 生成文件Key
132         /// </summary>
133         /// <param name="controllerContext">ControllerContext</param>
134         /// <returns>文件Key</returns>
135         protected virtual string GenerateKey(ControllerContext controllerContext)
136         {
137             var url = controllerContext.HttpContext.Request.Url.ToString();
138 
139             if (string.IsNullOrWhiteSpace(url))
140             {
141                 return null;
142             }
143 
144             var th = new TigerHash();
145             var data = th.ComputeHash(Encoding.Unicode.GetBytes(url));
146             var key = Convert.ToBase64String(data, Base64FormattingOptions.None);
147             key = HttpUtility.UrlEncode(key);
148 
149             return key;
150         }
151 
152         /// <summary>
153         /// 获取静态的文件信息
154         /// </summary>
155         /// <param name="controllerContext">ControllerContext</param>
156         /// <returns>缓存文件信息</returns>
157         protected virtual FileInfo GetCacheFileInfo(ControllerContext controllerContext)
158         {
159             var fileName = string.Empty;
160 
161             if (string.IsNullOrWhiteSpace(FileName))
162             {
163                 var key = GenerateKey(controllerContext);
164 
165                 if (!string.IsNullOrWhiteSpace(key))
166                 {
167                     fileName = Path.Combine(CacheDirectory, string.IsNullOrWhiteSpace(Suffix) ? key : string.Format("{0}.{1}", key, Suffix));
168                 }
169             }
170             else
171             {
172                 fileName = Path.Combine(CacheDirectory, FileName);
173             }
174 
175             return new FileInfo(fileName);
176         }
177 
178         #endregion
179     }

如果大家对于生成的文件和目录有特殊的要求,那可以重写GetCacheFileInfo方法,比如按照日期生成目录等等更复杂的目录和文件结构。当然以上代码只是提供了生成静态页的方法,但是访问如何解决呢? 访问静态文件和规则就需要在HttpApplication的Application_BeginRequest实现了。首先可以设置需要静态化访问的路由地址以html结尾。下面的是一个用于首页的静态化访问的实现,很简单,当然你可以实现比较复杂的逻辑,比如根据文件时间来判断是否应该访问静态文件等等。


 1         protected void Application_BeginRequest(object sender, EventArgs e)
 2         {
 3             StaticContentRewrite();
 4         }
 5 
 6         /// <summary>
 7         /// 处理静态发布内容
 8         /// </summary>
 9         private void StaticContentRewrite()
10         {
11             if (Context.Request.FilePath == "/" || Context.Request.FilePath.StartsWith("/index.html", StringComparison.OrdinalIgnoreCase))
12             {
13                 if (File.Exists(Server.MapPath("index.html")))
14                 {
15                     Context.RewritePath("index.html");
16                 }
17             }

18         }

asp.net mvc3的静态化实现的更多相关文章

  1. 利用ResultFilter实现asp.net mvc3 页面静态化

    为了提高网站性能.和网站的负载能力,页面静态化是一种有效的方式,这里对于asp.net mvc3 构架下的网站,提供一种个人认为比较好的静态话方式. 实现原理是通过mvc提供的过滤器扩展点实现页面内容 ...

  2. Asp.Net MVC页面静态化功能实现一:利用IHttpModule和ResultFilter

    由于公司现在所采用的是一套CMS内容管理系统的框架,所以最近项目中有一个需求提到要求实现页面静态化的功能.在网上查询了一些资料和文献,最后采用的是小尾鱼的池塘提供的 利用ResultFilter实现a ...

  3. ASP.NET MVC 页面静态化操作的思路

    本文主要讲述了在asp.net mvc中,页面静态化的几种思路和方法.对于网站来说,生成纯html静态页面除了有利于seo外,还可以减轻网站的负载能力和提高网站性能.在asp.net mvc中,视图的 ...

  4. Asp.Net MVC页面静态化功能实现二:用递归算法来实现

    上一篇提到采用IHttpModule来实现当用户访问网站的时候,通过重新定义Response.Filter来实现将返回给客户端的html代码保存,以便用户下一次访问是直接访问静态页面. Asp.Net ...

  5. Asp.Net MVC页面静态化功能实现一:利用IHttpModule,摒弃ResultFilter

    上一篇有提到利用IHttpModule和ResultFilter实现页面静态化功能.后来经过一些改动,将ResultFilter中要实现的功能全部转移到IHttpModule中来实现 Asp.Net ...

  6. ASP.NET 页面双向静态化

    而我们预期的结果应该如下图,实际只请求两次. 用301重定向可以解决该循环请求产生的问题. OK, let's begin. 本文的Demo和Source是基于上一篇的,如果下面的一些文件或文件夹没有 ...

  7. Asp.net动态页面静态化之初始NVelocity模板引擎

    Asp.net动态页面静态化之初始NVelocity模板引擎 静态页面是网页的代码都在页面中,不须要运行asp,php,jsp,.net等程序生成client网页代码的网页,静态页面网址中一般不含&q ...

  8. 利用ResultFilter实现asp.net mvc 页面静态化

    为了提高网站性能.和网站的负载能力,页面静态化是一种有效的方式,这里对于asp.net mvc3 构架下的网站,提供一种个人认为比较好的静态话方式. 实现原理是通过mvc提供的过滤器扩展点实现页面内容 ...

  9. Asp.net Mvc 页面静态化

    http://www.cnblogs.com/gowhy/archive/2013/01/01/2841472.html

随机推荐

  1. 算法导论 第六章 2 优先队列(python)

    优先队列:     物理结构: 顺序表(典型的是数组){python用到list}     逻辑结构:似完全二叉树 使用的特点是:动态的排序..排序的元素会增加,减少#和快速排序对比 快速一次排完 增 ...

  2. CentOS7 设置代理

    大多数公司的网络都使用局域网加代理上网,也就是说上外网必须使用公司指定的代理服务器,这有几个好处: 1. 首先代理可以一定程度提高浏览速度,因为可以将更多的网页缓存在代理服务器上,需要的时候直接拿就很 ...

  3. NYOJ-613//HDU-1176-免费馅饼,数字三角形的兄弟~~

    免费馅饼 时间限制:1000 ms  |  内存限制:65535 KB 难度:3 描述 都说天上不会掉馅饼,但有一天gameboy正走在回家的小径上,忽然天上掉下大把大把的馅饼.说来gameboy的人 ...

  4. hdu 2181暴搜

    #include<stdio.h> #include<string.h> #define N 30 int map[N][4],total; void dfs(int n,in ...

  5. hdu3709 Balanced Number 树形dp

    A balanced number is a non-negative integer that can be balanced if a pivot is placed at some digit. ...

  6. 【HDOJ6298】Maximum Multiple(数论)

    题意:给定n,求x,y,z三个整数,使得x|n,y|n,z|n,且xyz最小 n<=1e6 思路: 不定方程1/x+1/y+1/z=1 只有(2,3,6)(2,4,4) (3,3,3)三组正整数 ...

  7. 【CF766D】Mahmoud and a Dictionary(并查集)

    题意:有n个单词,给定m个关系,每个关系要么表示单词a与单词b相同,要么表示单词a与单词b相反. 并且“相同”与“相反”有性质:若a与b相同,b与c相同,则a与c相同(从而单词的相同关系是等价关系): ...

  8. 【BZOJ4517】排列计数(排列组合)

    题意:1-n的一个序列,其中有m个a[i]=i,求方案数 n,m<=1000000 题意:显然ANS=c(n,m)*d[n-m] d[i]为错排方案数=d[i-1]*n+(-1)^n ; ..] ...

  9. 库操作&表操作

    系统数据库 ps:系统数据库: mysql 授权库,主要存储系统用户的 权限信息 test MySQL数据库系统自动创建的 测试数据库 ination_schema 虚拟库,不占用磁盘空间,存储的是数 ...

  10. Codechef May Challenge 2015

    随便瞎写,其实没做出多少题: Chef and Cake 题目大概是用输入的数生成 一个数组并且生成出q个[X,Y]的询问, 数组长度N<=1000000,q<=10^7; 开始用线段树, ...