ASP.NET MVC 优化笔记 -<Cache 以及页面 压缩>

using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;

namespace MvcAppCache.Controllers
{

    /*
     * 
     * FireFox:可以在浏览器中输入 about:cache?device=disk 查看浏览器缓存数据
     * 
     * 1. 在 Action 中添加:
     *  Response.Cache.SetOmitVaryStar(true);
     *  防止缓存不稳定  200 与 304  不定期出现。
     * By: Rhythmk.cnblogs.com <王坤>
     */

    public class HomeController : Controller
    {
        //
        // GET: /Home/
        [OutputCache(Duration = 30, Location = OutputCacheLocation.ServerAndClient)]
        public ActionResult Index()
        {
            
            Response.Cache.SetOmitVaryStar(true);
            ViewBag.Time = DateTime.Now;

            return View();
        }

        /// <summary>
        ///  服务端缓存30S
        /// </summary>
        /// <returns></returns>
        [OutputCache(Duration=30,Location=OutputCacheLocation.ServerAndClient)]
        public ActionResult ServerCache()
        {
            Response.Cache.SetOmitVaryStar(true);
            ViewBag.Time = DateTime.Now;

            return View();
        }



        /*
         *     通过配置文件配置缓存时间
                <caching>
                     <outputCacheSettings>
                        <outputCacheProfiles>
                            <add name="Cache1Hour" duration="60" varyByParam="none"/>
                        </outputCacheProfiles>
                    </outputCacheSettings>
                </caching>
         * By: Rhythmk.cnblogs.com <王坤>
         */
        [OutputCache(CacheProfile = "Cache1Hour", Location = OutputCacheLocation.Client)]
        public ActionResult ConfigCache()
        {
            Response.Cache.SetOmitVaryStar(true);
            ViewBag.Time = DateTime.Now;

            return View();
        }


        [CompressFilter]
        public ActionResult Compress()
        {
            return View();
        }
        public ActionResult NoCompress()
        {
            return PartialView("Compress");
        }


    }

    /// <summary>
    /// 输出压缩
    /// </summary>
    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method)]
    public class CompressFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            /*
           OnActionExecuting 在 ActionFilterAttribute 类中其实什么都没有做  仅仅是一个空的虚方法。
           base.OnActionExecuting(filterContext);
             * By: Rhythmk.cnblogs.com <王坤>
           */
            HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];

            if (string.IsNullOrEmpty(acceptEncoding)) return;

            acceptEncoding = acceptEncoding.ToUpperInvariant();

            HttpResponseBase response = filterContext.HttpContext.Response;

            if (acceptEncoding.Contains("GZIP"))
            {
                response.AppendHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("DEFLATE"))
            {
                response.AppendHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
           
        }
       
    }
}

 Action 客户端浏览器缓存:

   /// <summary>
        ///  代码实现 304 缓存
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewBag.Message = "欢迎使用 ASP.NET MVC!";
            DateTime dt;
            if (DateTime.TryParse(Request.Headers["If-Modified-Since"], out dt))
            {
                // 注意:如果是20秒内,我就以304的方式响应。
                if ((DateTime.Now - dt).TotalSeconds < 20.0)
                {
                    Response.StatusCode = 304;
                    return View();
                }
            }

            ViewBag.Time = DateTime.Now.ToString();
             

            // 注意这个调用,它可以产生"Last-Modified"这个响应头,浏览器在收到这个头以后,
            // 在后续对这个页面访问时,就会将时间以"If-Modified-Since"的形式发到服务器
            // 这样,上面代码的判断就能生效。
            Response.Cache.SetLastModified(DateTime.Now);
            return View();
        }

 

 

静态文件缓存: 

   VS 自带的调试机是不支持此功能IIS 7 默认支持静态文件缓存的。

   也可以通过 IIS 7  站点 右边选择 “输出缓存”进行配置指定。

 

posted @ 2013-04-18 10:29  Rhythmk  阅读(561)  评论(3编辑  收藏  举报
Rhythmk 个人笔记