Exemple #1
0
    private const bool IsCompress = true; //需要压缩
    public void Compress(HttpContext context)
    {
        HttpRequest request = context.Request;
        HttpResponse response = context.Response;

        string cachekey = string.Empty;

        string type = request.Url.Query.Substring(request.Url.Query.LastIndexOf(".")+1);
        if (!string.IsNullOrEmpty(type) && (type == "css" || type == "js"))
        {
            if (type == "js")
            {
                response.ContentType = "text/javascript";

            }
            else if (type == "css")
            {
                response.ContentType = "text/css";
            }

            var paths = request.QueryString[0].Split(',');
            cachekey = string.Format(CacheKeyFormat, paths[paths.Length-1].Split('-')[0]+"_"+type);
            CompressCacheItem cacheItem = HttpRuntime.Cache[cachekey] as CompressCacheItem;
            if (cacheItem == null)
            {
                string content = string.Empty;
                //string[] files = Directory.GetFiles(path, "*." + type);
                StringBuilder sb = new StringBuilder();
               
                foreach (var item in paths)
                {
                    string filename = context.Server.MapPath(item.Contains("."+type)?item:item+"."+type);
                    if (File.Exists(filename))
                    {
                        string readstr = File.ReadAllText(filename, Encoding.UTF8);
                        sb.Append(readstr);
                    }
                }

                content = sb.ToString();

                // 开始压缩文件
                if (IsCompress)
                {
                    if (type.Equals("js"))
                    {
                        content = new JavaScriptCompressor().Compress(content);
                    }
                    else if (type.Equals("css"))
                    {
                        content = new CssCompressor().Compress(content);
                    }
                }

                //输入到客户端还可以进行Gzip压缩 ,这里就省略了

                cacheItem = new CompressCacheItem() { Type = type, Content = content, Expires = DateTime.Now.AddMinutes(30) };
                HttpRuntime.Cache.Insert(cachekey, cacheItem, null, cacheItem.Expires, TimeSpan.Zero);
            }

            string ifModifiedSince = request.Headers["If-Modified-Since"];
            if (!string.IsNullOrEmpty(ifModifiedSince)&&TimeSpan.FromTicks(cacheItem.Expires.Ticks - DateTime.Parse(ifModifiedSince).Ticks).Seconds < 0)
            {
                response.StatusCode = (int)System.Net.HttpStatusCode.NotModified;
                response.StatusDescription = "Not Modified";
            }
            else
            {
                response.Write(cacheItem.Content);
                SetClientCaching(response, cacheItem.Expires);
            }
        }

    }