代码存档

    public static bool IsCached(HttpContext context, TimeSpan cacheDuration)
    {
        var modifiedSince = context.Request.Headers["If-Modified-Since"];
        if (!string.IsNullOrEmpty(modifiedSince))
        {
            modifiedSince = Regex.Replace(modifiedSince, @";.*$", "");//ie6
        }
        DateTime modified;
        if (DateTime.TryParse(modifiedSince, out modified) && modified.Add(cacheDuration) > DateTime.Now)
        {
            context.Response.StatusCode = 304;
            context.Response.Status = "304 Not Modified";
            return true;
        }
        return false;
    }
    public static void SetCachedHeader(HttpContext context, TimeSpan cacheDuration)
    {
        FieldInfo maxAge = context.Response.Cache.GetType().GetField("_maxAge",
BindingFlags.Instance | BindingFlags.NonPublic);
        maxAge.SetValue(context.Response.Cache, cacheDuration);
        //context.Response.Cache.SetMaxAge(cacheDuration);
        context.Response.Cache.SetETag(string.Empty);
        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.Cache.SetLastModified(DateTime.Now);
        context.Response.Cache.SetExpires(DateTime.Now.Add(cacheDuration));
        context.Response.Cache.AppendCacheExtension(
                "must-revalidate, proxy-revalidate");
    }
    public static void Cached(HttpContext context)
    {
        Cached(context, TimeSpan.FromMinutes(10));
    }

    public static void Cached(HttpContext context, TimeSpan cacheDuration)
    {
        if (!IsCached(context, cacheDuration))
        {
            SetCachedHeader(context, cacheDuration);
        }
        else
        {
            context.Response.End();
        }

    }
    public static void GZIP(HttpContext context)
    {
        string acceptEncoding = context.Request.Headers["Accept-Encoding"];

        if (!String.IsNullOrEmpty(acceptEncoding))
        {
            acceptEncoding = acceptEncoding.ToString().ToUpperInvariant();
            //如果头部里有包含"GZIP”,"DEFLATE",表示你浏览器支持 GZIP,DEFLATE压缩
            if (acceptEncoding.Contains("GZIP"))
            {
                //向输出流头部添加压缩信息
                context.Response.AppendHeader("Content-encoding", "gzip");
                context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("DEFLATE"))
            {
                //向输出流头部添加压缩信息
                context.Response.AppendHeader("Content-encoding", "deflate");
                context.Response.Filter = new DeflateStream(context.Response.Filter, CompressionMode.Compress);
            }
        }
    }

posted @ 2010-10-19 15:49 MicroCoder 阅读(...) 评论(...) 编辑 收藏